X-Git-Url: https://jfr.im/git/z_archive/twitter.git/blobdiff_plain/1b31d642c54e09dc8f8a1ca49c934d6990f2ab33..098660ce6ca34597e97f074b3af48f64dcf3ea03:/twitter/oauth.py diff --git a/twitter/oauth.py b/twitter/oauth.py index 75ac3e3..be47e96 100644 --- a/twitter/oauth.py +++ b/twitter/oauth.py @@ -1,20 +1,34 @@ +from __future__ import print_function + from twitter.auth import Auth from time import time from random import getrandbits -from time import time -import urllib + +try: + import urllib.parse as urllib_parse +except ImportError: + import urllib2 as urllib_parse + import hashlib import hmac +import base64 + def write_token_file(filename, oauth_token, oauth_token_secret): + """ + Write a token file to hold the oauth token and oauth token secret. + """ oauth_file = open(filename, 'w') - print >> oauth_file, oauth_token - print >> oauth_file, oauth_token_secret + print(oauth_token, file=oauth_file) + print(oauth_token_secret, file=oauth_file) oauth_file.close() def read_token_file(filename): + """ + Read a token file and return the oauth token and oauth token secret. + """ f = open(filename) return f.readline().strip(), f.readline().strip() @@ -46,16 +60,17 @@ class OAuth(Auth): params['oauth_timestamp'] = str(int(time())) params['oauth_nonce'] = str(getrandbits(64)) - enc_params = urlencode_noplus(sorted(params.iteritems())) + enc_params = urlencode_noplus(sorted(params.items())) - key = self.consumer_secret + "&" + urllib.quote(self.token_secret, '') + key = self.consumer_secret + "&" + urllib_parse.quote(self.token_secret, '') message = '&'.join( - urllib.quote(i, '') for i in [method.upper(), base_url, enc_params]) - - signature = hmac.new( - key, message, hashlib.sha1).digest().encode('base64')[:-1] - return enc_params + "&" + "oauth_signature=" + urllib.quote(signature, '') + urllib_parse.quote(i, '') for i in [method.upper(), base_url, enc_params]) + + signature = (base64.b64encode(hmac.new( + key.encode('ascii'), message.encode('ascii'), hashlib.sha1) + .digest())) + return enc_params + "&" + "oauth_signature=" + urllib_parse.quote(signature, '') def generate_headers(self): return {} @@ -67,18 +82,18 @@ class OAuth(Auth): def urlencode_noplus(query): if hasattr(query,"items"): # mapping objects - query = query.items() - + query = list(query.items()) + encoded_bits = [] for n, v in query: # and do unicode here while we are at it... - if isinstance(n, unicode): + if isinstance(n, str): n = n.encode('utf-8') else: n = str(n) - if isinstance(v, unicode): + if isinstance(v, str): v = v.encode('utf-8') else: v = str(v) - encoded_bits.append("%s=%s" % (urllib.quote(n, ""), urllib.quote(v, ""))) + encoded_bits.append("%s=%s" % (urllib_parse.quote(n, ""), urllib_parse.quote(v, ""))) return "&".join(encoded_bits)