Http post Curl in python

I am having trouble understanding how to issue an HTTP POST request using curl from within python.

I am attaching a message to an open facebook schedule. Here is an example that they give that I would like to accurately reproduce in python.

curl -F 'access_token=...' \ -F 'message=Hello, Arjun. I like this new API.' \ https://graph.facebook.com/arjun/feed 

Can someone help me figure this out?

+7
source share
2 answers

You can use httplib for POST using Python or a higher level urllib2

 import urllib params = {} params['access_token'] = '*****' params['message'] = 'Hello, Arjun. I like this new API.' params = urllib.urlencode(params) f = urllib.urlopen("https://graph.facebook.com/arjun/feed", params) print f.read() 

There is also a special top-level Python library for Facebook that does all the POST-IN for you.

https://github.com/pythonforfacebook/facebook-sdk/

https://github.com/facebook/python-sdk

+14
source

Why do you use curl in the first place?

Python has extensive libraries for Facebook and includes libraries for web requests; calling another program and receiving output is not required.

Nevertheless,

First from a Python document

data can be a string indicating additional data to send to the server, or None if such data is not required. Currently, HTTP requests are only those that use data; The HTTP request will be POST instead of GET when a data parameter is provided . data should be a buffer in the standard format application/x-www-form-urlencoded . The urllib.urlencode () function accepts a mapping or sequence of 2 sets and returns a string in this format. The urllib2 module sends HTTP / 1.1 requests with a connection: the private header is enabled.

So,

 import urllib2, urllib parameters = {} parameters['token'] = 'sdfsdb23424' parameters['message'] = 'Hello world' target = 'http://www.target.net/work' parameters = urllib.urlencode(parameters) handler = urllib2.urlopen(target, parameters) while True: if handler.code < 400: print 'done' # call your job break elif handler.code >= 400: print 'bad request or error' # failed break 
+1
source

All Articles