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