]> jfr.im git - z_archive/twitter.git/blob - twitter/oauth2.py
Allow storage of date in ISO (RFC 3339) format
[z_archive/twitter.git] / twitter / oauth2.py
1 """
2 Visit the Twitter developer page and create a new application:
3
4 https://dev.twitter.com/apps/new
5
6 This will get you a CONSUMER_KEY and CONSUMER_SECRET.
7
8 Twitter only supports the application-only flow of OAuth2 for certain
9 API endpoints. This OAuth2 authenticator only supports the application-only
10 flow right now. If twitter supports OAuth2 for other endpoints, this
11 authenticator may be modified as needed.
12
13 Finally, you can use the OAuth2 authenticator to connect to Twitter. In
14 code it all goes like this::
15
16 twitter = Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN))
17
18 # Now work with Twitter
19 twitter.search.tweets(q='keyword')
20
21 """
22
23 from __future__ import print_function
24
25 try:
26 from urllib.parse import quote, urlencode
27 except ImportError:
28 from urllib import quote, urlencode
29
30 from base64 import b64encode
31 from twitter.auth import Auth
32
33
34 class OAuth2(Auth):
35 """
36 An OAuth2 application-only authenticator.
37 """
38 def __init__(self, consumer_key=None, consumer_secret=None,
39 bearer_token=None):
40 """
41 Create an authenticator. You can supply consumer_key and
42 consumer_secret if you are requesting a bearer_token. Otherwise
43 you must supply the bearer_token.
44 """
45 self.bearer_token = None
46 self.consumer_key = None
47 self.consumer_secret = None
48
49 if bearer_token:
50 self.bearer_token = bearer_token
51 elif consumer_key and consumer_secret:
52 self.consumer_key = consumer_key
53 self.consumer_secret = consumer_secret
54 else:
55 raise MissingCredentialsError(
56 'You must supply either a bearer token, or both a '
57 'consumer_key and a consumer_secret.')
58
59 def encode_params(self, base_url, method, params):
60
61 return urlencode(params)
62
63 def generate_headers(self):
64 if self.bearer_token:
65 headers = {
66 b'Authorization': 'Bearer {0}'.format(
67 self.bearer_token).encode('utf8')
68 }
69
70 elif self.consumer_key and self.consumer_secret:
71
72 headers = {
73 b'Content-Type': (b'application/x-www-form-urlencoded;'
74 b'charset=UTF-8'),
75 b'Authorization': 'Basic {0}'.format(
76 b64encode('{0}:{1}'.format(
77 quote(self.consumer_key),
78 quote(self.consumer_secret)).encode('utf8')
79 ).decode('utf8')
80 ).encode('utf8')
81 }
82
83 else:
84 raise MissingCredentialsError(
85 'You must supply either a bearer token, or both a '
86 'consumer_key and a consumer_secret.')
87
88 return headers
89
90
91 class MissingCredentialsError(Exception):
92 pass