I have a JS script in HTML file which collects input provided by a user. Using the inputed values I form a string and send it to backend Python script via an AJAX call:
$.ajax({
type: "POST",
url: "/cgi-bin/backend.py",
}); data: { 'form_data' : datastring}
The datastring has a value like:
age=9&country=US&buyer=Sample
I see in FireBug the same getting POSTed as:
form_data=age%3D9%26country%3DUS%26....
In my Python backend code I have a check to validate and get the CGI 'form_data' variable value:
if self.cgi.has_key ("form_data"):
But surprisingly the code does not enters this 'if' code? Also how does the values in the datastring gets changed to 'age%3D9%26'? If I split the CGI variable by '&' and the parse the splited values by '=' will I be able to get the CGI name value pairs?
First of all the data your sending is getting urlencoded and that is why it looks that way.
You will also need to post your python code if you need any more help with this question. That aside I would advice you to use a python web framework such as Flask or bottle instead of using cgi.
Related
I am a new programmer and I'm learning the request module. I'm stuck on the fact that I don't know how to get a specific part of a json response, I think it's called a header? or its the thing inside of a header? I'm not sure. But the API returns simple json code. This is the api
https://mcapi.us/server/status?ip=mc.hypixel.net
for more of a example, lets say it returns this json code from the api
{"status":"success","online":true"}
And I wanted to get the "online" response, how would I do that?
And this is the code im currently working with.
import requests
def main():
ask = input("IP : ")
response = requests.get('https://mcapi.us/server/status?ip=' + ask)
print(response.content)
main()
And to be honest, I don't even know if this is json. I think it is but the api page says its cors? if it isn't I'm sorry.
In your example you have a dictionary with key "online"
You need to parse it first with .json() and then you can get it in form dict[key]
In your case
response = requests.get('https://mcapi.us/server/status?ip=' + ask).json()
print(response["online"])
or in case of actual content
response = requests.get('https://mcapi.us/server/status?ip=' + ask).json()
print(response["content"])
I've just discovered something strange. When downloading data from facebook with GET using the requests 2.18.4 library, I get error when I just use
requests.get('https://.../{}/likes?acces_token={}'.format(userID,token))
into which I parse the user ID and access - the API does not read the access token correctly.
But, it works fine as
requests.get('https://../{}'.format(userID), params={"access_token":token})
Or it works when I copy paste the values in the appropriate fields by hand in the python console.
So my hypothesis is that it has something to with how the token string got parsed using the params vs the string. But what I don't understand at all, why would that be the case? Or is ? character somehow strange in this case?
Double check if both the URLs are the same (in your post they differ by the /likes substring).
Then you can check how the library requests concatenated parameters from the params argument:
url = 'https://facebook.com/.../{}'.format(userID)
r = requests.Request('GET', url, params={"access_token":token})
pr = r.prepare()
print pr.url
I'm trying to understand what exactly I'm getting back when I make a POST request using the Requests module — is it always JSON? Seems like every response I get appears to be JSON, but I'm not sure.
Where r is my response object, when I do:
print r.apparent_encoding
It always seems to return ascii
And when I try type():
>>>print type(r)
<class 'requests.models.Response'
I pasted the output from print r.text into a JSON validator, and it reported no errors. So should I assume Requests is providing my with JSON objects here?
A response can be anything. If you've posted to a REST endpoint, it will usually respond with JSON. If so, requests will detect that and allow you to decode it via the .json() method.
But it's perfectly possible for you to post to a normal web URL, in effect pretending to be a browser, and unless the server is doing something really clever it will just respond with the standard HTML it would serve to the browser. In that case, doing response.json() will raise a ValueError.
No, the response text for a POST request is totally up to the web service. A good REST API will always respond with JSON, but you will not always get that.
Example
A common pattern in PHP is
<?php
$successful_whatever = false;
if (isset($_POST['whatever'])) {
# put $_POST['whatever'] in a database
$successful_whatever = true;
}
echo $twig->render('gallery.twig',
array('successful_whatever' => $successful_whatever));
?>
As you can see the response text will be a rendered template (HTML). I'm not saying it is good, just that it is common.
I recently, started working on the google app engine and am facing the following problem:
I have a main.py where my user sees his own comments + those of others. Now, I need to add an EditComment.py where a user is directed when he wants to edit his code.
I am working with the guestbook application only, and to actually fetch the selected comment I need both guestbook name and the content of the comment. How do I create this url?
In other words, I need to create a url like
\edit?guestbook="Family"&content="helloworld"
I tried this
//I need to send guestbook_name and content of greeting in order to fetch the row from
//the database
//So, I show the text of the greeting and give a url to edit page
content_toSend = {'guestbook_name':guestbook_name,'content':greeting.content}
self.response.write('<blockquote>%s</blockquote>' %
(content_toSend,greeting.content))
//But the other side handler receives only the first variable of the dict in the get request
so that the user can click on a greeting and be directed to the edit page. But the get request just sends the first var(guestbook_name) in the url. How do I send the whole dictionary?
Edit : I had tired urllib.urlencode but the handler in webapp2 requires a dict and so that didn't work
The method urlencode() of urllib standard library can be useful.
edit with example:
content_toSend = urllib.urlencode({
'guestbook_name' : guestbook_name,
'content' : greeting.content
})
If you know that you are going to have these two variables in dictionary why dont u try this
self.response.write('<blockquote>%s</blockquote>' %
(content_toSend['guestbook_name'],content_toSend['content'],greeting.content))
Suppose I have the following HTML input element within a form:
<input name="title_input" type="text" id="missing_value" title="Title">
If I want to submit a POST:
s = requests.Session()
s.get(url)
postResult = s.post(url, {'title_input':'This Is the Name of the Title'})
Even though the element has a missing value attribute, will this POST still work correctly?
I.e. will Python append value="This Is The Name of the Title" in the element even though it's missing from the original HTML?
Even though the element has a missing value attribute, will this POST still work correctly?
Yes It will. POST request will be done without obtaining HTML at all
You don't need this line for POST request
s.get(url)
I.e. will Python append value="This Is The Name of the Title" in the element
No Python will not append anything. Python even will not analyze get content (if get request is done)
It just open tcp connection and send data.
You haven't explained what that HTML is or how it relates to the Python code, but in any case the HTML doesn't seem to have anything to do with anything. The POST request is made by the requests module, not by HTML, so it gets its value from whatever you put into the parameters to the post() call.