]> jfr.im git - z_archive/twitter.git/blob - twitter/oauth2.py
Fix ResourceWarning on read_bearer_toke_file func
[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, MissingCredentialsError
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 bearer_token = f.readline().strip()
50 f.close()
51 return bearer_token
52
53 class OAuth2(Auth):
54 """
55 An OAuth2 application-only authenticator.
56 """
57 def __init__(self, consumer_key=None, consumer_secret=None,
58 bearer_token=None):
59 """
60 Create an authenticator. You can supply consumer_key and
61 consumer_secret if you are requesting a bearer_token. Otherwise
62 you must supply the bearer_token.
63 """
64 self.bearer_token = bearer_token
65 self.consumer_key = consumer_key
66 self.consumer_secret = consumer_secret
67
68 if not (bearer_token or (consumer_key and consumer_secret)):
69 raise MissingCredentialsError(
70 'You must supply either a bearer token, or both a '
71 'consumer_key and a consumer_secret.')
72
73 def encode_params(self, base_url, method, params):
74 return urlencode(params)
75
76 def generate_headers(self):
77 if self.bearer_token:
78 headers = {
79 b'Authorization': 'Bearer {0}'.format(
80 self.bearer_token).encode('utf8')
81 }
82 else:
83 headers = {
84 b'Content-Type': (b'application/x-www-form-urlencoded;'
85 b'charset=UTF-8'),
86 b'Authorization': 'Basic {0}'.format(
87 b64encode('{0}:{1}'.format(
88 quote(self.consumer_key),
89 quote(self.consumer_secret)).encode('utf8')
90 ).decode('utf8')
91 ).encode('utf8')
92 }
93 return headers