Skip to content

Instantly share code, notes, and snippets.

@michaelhelmick
Created January 4, 2012 02:17
Show Gist options
  • Save michaelhelmick/1558113 to your computer and use it in GitHub Desktop.
Save michaelhelmick/1558113 to your computer and use it in GitHub Desktop.
Post an image to API with Python OAuth
'''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
@michaelhelmick
Copy link
Author

michaelhelmick commented Jan 4, 2012 via email

@ryanmcgrath
Copy link

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