Skip to content

Instantly share code, notes, and snippets.

@michaelhelmick
Created March 8, 2012 17:11
Show Gist options
  • Save michaelhelmick/2002119 to your computer and use it in GitHub Desktop.
Save michaelhelmick/2002119 to your computer and use it in GitHub Desktop.
#requests-oauth header produces:
{
'Authorization': 'OAuth realm="", oauth_nonce="50997118", oauth_timestamp="1331135338", oauth_consumer_key="********", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="********", oauth_signature="IT1qsDRpc0wHXxo0q9IscLSpGaU%3D"'
}
#faux_req.to_header() produces:
{
'Authorization': u 'OAuth realm="", oauth_body_hash="2jmj7l5rSw0yVb%2FvlWAYkK%2FYBwk%3D", oauth_nonce="74348031731097571737250753271922149182231", oauth_timestamp="1331078125", oauth_consumer_key="********", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="********", oauth_signature="jv7TI4Xg3VK3x0IqrpRpL1u10z0%3D"'
}
OAuthHook.consumer_key = 'my_consumer_key'
OAuthHook.consumer_secret = 'my_consumer_secret'
self.client = None
if self.oauth_token is not None and self.oauth_secret is not None:
self.oauth_hook = OAuthHook(self.oauth_token, self.oauth_secret)
self.client = requests.session(hooks={'pre_request': self.oauth_hook})
# for posting an image to I need to send the OAuth Params in the header
self.oauth_hook.header_auth = True
self.client = requests.session(hooks={'pre_request': self.oauth_hook})
response = self.client.post(url, data=params, files=file_, headers=self.headers)
print response.content
'''
response.content
{"request":"\/1\/statuses\/update_with_media.json","error":"Could not authenticate you."}
'''
#Previously, in the class I was using requests to upload the file and junk and was doing this:
def _media_update(self, url, file_, params=None):
params = params or {}
oauth_params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(length=41),
'oauth_timestamp': int(time.time()),
}
#create a fake request with your upload url and parameters
faux_req = oauth.Request(method='POST', url=url, parameters=oauth_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
#print 'fake headers: ', faux_req.to_header()
self.headers.update(faux_req.to_header())
req = requests.post(url, data=params, files=file_, headers=self.headers)
return req.content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment