Using Python-Oauth2 To Access OAuth Protected Resources
Most of the examples I found for python-oauth2 show how to use the library to request and approve tokens, but not how to use the access token to access a protected resource (ie. how to actually make a call to the service you’re trying to access). Here’s an example:
import oauth2 as oauth
consumer = oauth.Consumer('consumer-key-here','consumer-secret-here')
token = oauth.Token('access-key-here','access-key-secret-here')
client = oauth.Client(consumer, token)
response = client.request('http://someservice.com/api/something/')
And here’s how you make a POST call:
import urllib
response, content = myclient.request("http://someservice.com/api/something/", \
method="POST", body=urllib.urlencode({'name': 'value', 'another_name': 'another value'}) )
Manage your expenses via Email, SMS, iPhone, Twitter, Voice (Call and say your expense), IM (Yahoo, AIM, MSN), or Web.
Comments(4)
Thanks so much… it’s amazing that ten months after your post, python-oauth2 still doesn’t provide an example of how to access a protected resource!
Excellent post complementing usage of python-oauth2 to post tweets
postapi = ‘http://api.twitter.com/1/statuses/update.json’
def oauth_post(postapi, ckey, csecret, akey, asecret, status):
consumer = oauth.Consumer(key=ckey, secret=csecret)
token = oauth.Token(key=akey, secret=asecret)
client = oauth.Client(consumer, token)
resp, content = client.request(
postapi,
method
body = urllib.urlencode({’status’: status, ‘wrap_links’: True}),
#headers=http_headers,
#force_auth_header=True
)
return resp, content
Excellent post complementing usage of python-oauth2 to post tweets
postapi = ‘http://api.twitter.com/1/statuses/update.json’
def oauth_post(postapi, status, ckey, csecret, akey, asecret):
consumer = oauth.Consumer(key=ckey, secret=csecret)
token = oauth.Token(key=akey, secret=asecret)
client = oauth.Client(consumer, token)
resp, content = client.request(
postapi,
method=’POST’,
body = urllib.urlencode({’status’: status, ‘wrap_links’: True}),
)
return resp, content
Thank you! You saved me!
And for those dealing with shitty APIs (…) that return a token key (but not a token secret), try passing the received token as the token key, and an empty string as the token secret… That was a great hour wasted…!
Cheer