Created
January 4, 2012 02:17
-
-
Save michaelhelmick/1558113 to your computer and use it in GitHub Desktop.
Post an image to API with Python OAuth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''encode_multipart_formdata taken from @ryanmcgrath `twython`''' | |
def post_image(self): | |
files = [("photo", 'image.jpg', open('/path/to/image.jpg', 'rb').read())] | |
params = { | |
'oauth_version': "1.0", | |
'oauth_nonce': oauth.generate_nonce(), | |
'oauth_timestamp': int(time.time()), | |
'oauth_token': self.oauth_token, | |
'oauth_consumer_key': self.api_key, | |
} | |
#create a fake request with your upload url and parameters | |
faux_req = oauth.Request(method='POST', url=self.upload_api_url, parameters=params) | |
#sign the fake request. | |
signature_method = oauth.SignatureMethod_HMAC_SHA1() | |
faux_req.sign_request(signature_method, self.consumer, self.token) | |
#create a dict out of the fake request signed params | |
params = dict(parse_qsl(faux_req.to_postdata())) | |
content_type, body = self.encode_multipart_formdata(params, files) | |
headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} | |
r = urllib2.Request('%s' % self.upload_api_url, body, headers) | |
return urllib2.urlopen(r).read() | |
@staticmethod | |
def encode_multipart_formdata(fields, files): | |
import mimetools | |
import mimetypes | |
BOUNDARY = mimetools.choose_boundary() | |
CRLF = '\r\n' | |
L = [] | |
for (key, value) in fields.items(): | |
L.append('--' + BOUNDARY) | |
L.append('Content-Disposition: form-data; name="%s"' % key) | |
L.append('') | |
L.append(value) | |
for (key, filename, value) in files: | |
L.append('--' + BOUNDARY) | |
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) | |
L.append('Content-Type: %s' % mimetypes.guess_type(filename)[0] or 'application/octet-stream') | |
L.append('') | |
L.append(value) | |
L.append('--' + BOUNDARY + '--') | |
L.append('') | |
body = CRLF.join(L) | |
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY | |
return content_type, body |
Yeah, I'll fork it sometime tomorrow!
…Sent from my iPhone
On Jan 3, 2012, at 10:55 PM, Ryan McGrath ***@***.*** wrote:
Nice! Any chance of throwing this into Twython? Seems really clean, quite impressed. ;)
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/1558113
Awesome! Let me know if I can help in any way.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! Any chance of throwing this into Twython? Seems really clean, quite impressed. ;)