Last active
December 26, 2015 14:39
-
-
Save charlycoste/7167140 to your computer and use it in GitHub Desktop.
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
# import oauth2 | |
import oauth2 as oauth | |
import urlparse | |
# defining endpoints | |
request_token_url = '' | |
authorize_url = '' | |
access_token_url = '' | |
# defining variables | |
consumer_key = '' | |
consumer_secret = '' | |
# creating consumer | |
consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) | |
# creating client from consumer | |
client = oauth.Client(consumer) | |
# requesting a token | |
response, content = client.request(request_token_url, 'GET') | |
# If status different from 200, then it failed | |
if response['status'] != '200': | |
raise Exception('Invalid response: %s' % response['status']) | |
# If token request is sucessfull then we parse the content with urlparse | |
request_token = dict(urlparse.parse_qsl(content)) | |
# We add the oauth_token parameter to the authorize_url link | |
authorize_link = '%s?oauth_token=%s' % (authorize_url, request_token['oauth_token']) | |
# We display the link of the html page were we need to authorize the application | |
print authorize_link | |
accepted = 'n' | |
while accepted.lower() == 'n': | |
# you need to access the authorize_link via a browser, | |
# and proceed to manually authorize the consumer | |
accepted = raw_input('Have you authorized me? (y/n) ') | |
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) | |
client = oauth.Client(consumer, token) | |
response, content = client.request(access_token_url, 'POST') | |
if response['status'] != '200': | |
raise Exception('Invalid response: %s' % response['status']) | |
access_token = dict(urlparse.parse_qsl(content)) | |
# this is the token you should save for future uses | |
token = oauth.Token(access_token['oauth_token'], | |
access_token['oauth_token_secret']) | |
# | |
# Generic example | |
# | |
import urllib | |
client = oauth.Client(consumer, token) | |
body = urllib.urlencode({'param1': 'value1', 'param2': 'value2'}) | |
headers = {'content-type': 'application/x-www-form-urlencoded'} | |
response, content = client.request(request_url, 'POST', body, headers) | |
if response['status'] != good_status_code_for_this_action: | |
raise Exception('Action failed, status is: %s' % response['status']) | |
else: | |
print 'Action succes!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment