Skip to content

Instantly share code, notes, and snippets.

@scturtle
Last active December 11, 2015 19:18
Show Gist options
  • Save scturtle/4647486 to your computer and use it in GitHub Desktop.
Save scturtle/4647486 to your computer and use it in GitHub Desktop.
simple OAuth 1.0
# coding: utf-8
# ref: https://github.com/FanfouAPI/FanFouAPIDoc/wiki/Oauth
# http://open.weibo.com/wiki/OAuth
import os
import json
import random
import requests
import webbrowser
from time import time
from urllib import quote_plus
request_url = 'http://fanfou.com/oauth/request_token'
access_url = 'http://fanfou.com/oauth/access_token'
auth_url = 'http://fanfou.com/oauth/authorize?oauth_callback=oob&oauth_token='
consumer_key = 'ea24ee780fb55403236436e5ec1b9509'
consumer_secret = '673dc74d3d0cc6cb121a025e9dc73b44'
oauth_token = ''
oauth_token_secret = ''
nonce = lambda: random.getrandbits(50)
stamp = lambda: str(int(time()))
def hmacsha1(s):
import hmac, hashlib, base64
sigkey = consumer_secret + '&' + oauth_token_secret
hashed = hmac.new(sigkey, s, hashlib.sha1)
return base64.b64encode(hashed.digest())
def sign(method, url, params):
base_string = method + '&' + quote_plus(url) + '&' +\
quote_plus('&'.join('%s=%s' % item
for item in sorted(params.items())))
return hmacsha1(base_string)
def req(url, **params):
params.update(oauth_consumer_key=consumer_key,
oauth_token=oauth_token,
oauth_signature_method='HMAC-SHA1',
oauth_timestamp=stamp(),
oauth_nonce=nonce())
sig = sign('GET', url, params)
params.update(oauth_signature=sig)
r = requests.get(url, params=params)
if r.status_code != 200:
raise Exception('Error in requesting: ' + url)
return r
def oauth():
if os.path.exists('ff.json'):
globals().update(json.load(open('ff.json')))
return
r = req(request_url)
globals().update(dict(map(lambda t: t.split('='), r.text.split('&'))))
# for personal
webbrowser.open(auth_url + oauth_token)
PIN = raw_input("")
r = req(access_url, oauth_verifier=PIN)
globals().update(dict(map(lambda t: t.split('='), r.text.split('&'))))
json.dump(dict(oauth_token=oauth_token,
oauth_token_secret=oauth_token_secret),
open('ff.json','w'))
if __name__ == '__main__':
oauth()
data = json.loads(req('http://api.fanfou.com/statuses/user_timeline.json',
count=1, mode='lite').text)
print data[0]['text'].encode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment