]>
jfr.im git - z_archive/twitter.git/blob - twitter/oauth.py
1 from twitter
.auth
import Auth
4 from random
import getrandbits
11 def write_token_file(filename
, oauth_token
, oauth_token_secret
):
12 oauth_file
= open(filename
, 'w')
13 print >> oauth_file
, oauth_token
14 print >> oauth_file
, oauth_token_secret
17 def read_token_file(filename
):
19 return f
.readline().strip(), f
.readline().strip()
24 An OAuth authenticator.
26 def __init__(self
, token
, token_secret
, consumer_key
, consumer_secret
):
28 Create the authenticator. If you are in the initial stages of
29 the OAuth dance and don't yet have a token or token_secret,
30 pass empty strings for these params.
33 self
.token_secret
= token_secret
34 self
.consumer_key
= consumer_key
35 self
.consumer_secret
= consumer_secret
37 def encode_params(self
, base_url
, method
, params
):
38 params
= params
.copy()
41 params
['oauth_token'] = self
.token
43 params
['oauth_consumer_key'] = self
.consumer_key
44 params
['oauth_signature_method'] = 'HMAC-SHA1'
45 params
['oauth_version'] = '1.0'
46 params
['oauth_timestamp'] = str(int(time()))
47 params
['oauth_nonce'] = str(getrandbits(64))
49 enc_params
= urlencode_noplus(sorted(params
.iteritems()))
51 key
= self
.consumer_secret
+ "&" + urllib
.quote(self
.token_secret
, '')
54 urllib
.quote(i
, '') for i
in [method
.upper(), base_url
, enc_params
])
57 key
, message
, hashlib
.sha1
).digest().encode('base64')[:-1]
58 return enc_params
+ "&" + "oauth_signature=" + urllib
.quote(signature
, '')
60 def generate_headers(self
):
63 # apparently contrary to the HTTP RFCs, spaces in arguments must be encoded as
64 # %20 rather than '+' when constructing an OAuth signature (and therefore
65 # also in the request itself.)
66 # So here is a specialized version which does exactly that.
67 def urlencode_noplus(query
):
68 if hasattr(query
,"items"):
74 # and do unicode here while we are at it...
75 if isinstance(n
, unicode):
79 if isinstance(v
, unicode):
83 encoded_bits
.append("%s=%s" % (urllib
.quote(n
, ""), urllib
.quote(v
, "")))
84 return "&".join(encoded_bits
)