]> jfr.im git - z_archive/twitter.git/blobdiff - twitter/oauth.py
Use base64 library instead of .encode("base64")
[z_archive/twitter.git] / twitter / oauth.py
index 61b771d98200a3a654aaf3445355ca05fad05380..e9c790f9948bc3018130ced9c140505677e20a5c 100644 (file)
@@ -3,14 +3,38 @@ from twitter.auth import Auth
 from time import time
 from random import getrandbits
 from time import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
 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_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()
 
 
-# An OAuth implementation with various helpers...
 class OAuth(Auth):
+    """
+    An OAuth authenticator.
+    """
     def __init__(self, token, token_secret, consumer_key, consumer_secret):
+        """
+        Create the authenticator. If you are in the initial stages of
+        the OAuth dance and don't yet have a token or token_secret,
+        pass empty strings for these params.
+        """
         self.token = token
         self.token_secret = token_secret
         self.consumer_key = consumer_key
@@ -19,23 +43,26 @@ class OAuth(Auth):
     def encode_params(self, base_url, method, params):
         params = params.copy()
 
-        params['oauth_token'] = self.token
+        if self.token:
+            params['oauth_token'] = self.token
+
         params['oauth_consumer_key'] = self.consumer_key
         params['oauth_signature_method'] = 'HMAC-SHA1'
         params['oauth_version'] = '1.0'
         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 {}
@@ -47,18 +74,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)