I am trying to use urllib2.urlopen to perform GET and POST requests via the Facebook Graph API. I noticed from here: https://stackoverflow.com/questions/2690723/facebook-graph-api-and-django that I can perform GET request fairly easily.
And from here: How to send a POST request using django? and the Python docs http://docs.python.org/library/urllib2.html it seems that it needs the data param to perform a POST request.
But looking at the Facebook's API: http://developers.facebook.com/docs/reference/api/event/#invited it says
You can invite users to an event by issuing an HTTP POST to /EVENT_ID/invited/USER_ID
I am not sure how I could do that with urlopen, since opening this url directly is going to only check if the user has been invited, as mentioned on the API page:
You can check whether a specific user has been invited to an event by issuing an HTTP GET to /EVENT_ID/invited/USER_ID:
Appreciate the input.
request is a Python module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the urlopen function. This is capable of fetching URLs using a variety of different protocols.
urllib2 is deprecated in python 3. x. use urllib instaed.
The data returned by urlopen() or urlretrieve() is the raw data returned by the server. This may be binary data (such as an image), plain text or (for example) HTML. The HTTP protocol provides type information in the reply header, which can be inspected by looking at the Content-Type header.
2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2. Requests - Requests' is a simple, easy-to-use HTTP library written in Python.
It sounds like you want to send an empty POST request, even though urllib2.urlopen() only sends a post when you specify the data parameter.
It seems like it actually sends an empty POST if you set data="", and GET request only when data=None:
urllib2.urlopen("http://127.0.0.1:8000", data="")
"POST / HTTP/1.1" 501 -
urllib2.urlopen("http://127.0.0.1:8000", data=None)
"GET / HTTP/1.1" 200 -
Hope that helps. I got the response printouts from the little HTTP server they have an example for here: http://docs.python.org/library/simplehttpserver.html
Another way to send an empty POST is to create a Request and override its get_method. This is more work in this case, but may be cleaner in other cases (if you already have a Request, for example).
request = urllib2.Request(url)
request.get_method = lambda: 'POST'
urllib2.urlopen(request)
get_method is a method that returns the method to be used, so here we override it with a lambda function that returns 'POST'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With