Finally, you can use the OAuth authenticator to connect to Twitter. In
code it all goes like this::
+ from twitter import *
+
MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
oauth_dance("My App Name", CONSUMER_KEY, CONSUMER_SECRET,
from __future__ import print_function
-from time import time
from random import getrandbits
+from time import time
+
+from .util import PY_3_OR_HIGHER
try:
import urllib.parse as urllib_parse
from urllib.parse import urlencode
- PY3 = True
except ImportError:
import urllib2 as urllib_parse
from urllib import urlencode
- PY3 = False
import hashlib
import hmac
import base64
-from .auth import Auth
+from .auth import Auth, MissingCredentialsError
def write_token_file(filename, oauth_token, oauth_token_secret):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
+ if token_secret is None or consumer_secret is None:
+ raise MissingCredentialsError(
+ 'You must supply strings for token_secret and consumer_secret, not None.')
+
def encode_params(self, base_url, method, params):
params = params.copy()
# %20 rather than '+' when constructing an OAuth signature (and therefore
# also in the request itself.)
# So here is a specialized version which does exactly that.
+# In Python2, since there is no safe option for urlencode, we force it by hand
def urlencode_noplus(query):
- if not PY3:
+ if not PY_3_OR_HIGHER:
new_query = []
+ TILDE = '____TILDE-PYTHON-TWITTER____'
for k,v in query:
if type(k) is unicode: k = k.encode('utf-8')
+ k = str(k).replace("~", TILDE)
if type(v) is unicode: v = v.encode('utf-8')
+ v = str(v).replace("~", TILDE)
new_query.append((k, v))
query = new_query
- return urlencode(query).replace("+", "%20")
-
- return urlencode(query, safe='~').replace("+", "%20")
\ No newline at end of file
+ return urlencode(query).replace(TILDE, "~").replace("+", "%20")
+
+ return urlencode(query, safe='~').replace("+", "%20")