]>
jfr.im git - z_archive/twitter.git/blob - twitter/oauth2.py
2 Twitter only supports the application-only flow of OAuth2 for certain
3 API endpoints. This OAuth2 authenticator only supports the application-only
6 To authenticate with OAuth2, visit the Twitter developer page and create a new
9 https://dev.twitter.com/apps/new
11 This will get you a CONSUMER_KEY and CONSUMER_SECRET.
13 Exchange your CONSUMER_KEY and CONSUMER_SECRET for a bearer token using the
14 oauth2_dance function.
16 Finally, you can use the OAuth2 authenticator and your bearer token to connect
17 to Twitter. In code it goes like this::
19 twitter = Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN))
21 # Now work with Twitter
22 twitter.search.tweets(q='keyword')
26 from __future__
import print_function
29 from urllib
.parse
import quote
, urlencode
31 from urllib
import quote
, urlencode
33 from base64
import b64encode
34 from .auth
import Auth
36 def write_bearer_token_file(filename
, oauth2_bearer_token
):
38 Write a token file to hold the oauth2 bearer token.
40 oauth_file
= open(filename
, 'w')
41 print(oauth2_bearer_token
, file=oauth_file
)
44 def read_bearer_token_file(filename
):
46 Read a token file and return the oauth2 bearer token.
49 return f
.readline().strip()
53 An OAuth2 application-only authenticator.
55 def __init__(self
, consumer_key
=None, consumer_secret
=None,
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.
62 self
.bearer_token
= bearer_token
63 self
.consumer_key
= consumer_key
64 self
.consumer_secret
= consumer_secret
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.')
71 def encode_params(self
, base_url
, method
, params
):
72 return urlencode(params
)
74 def generate_headers(self
):
77 b
'Authorization': 'Bearer {0}'.format(
78 self
.bearer_token
).encode('utf8')
82 b
'Content-Type': (b
'application/x-www-form-urlencoded;'
84 b
'Authorization': 'Basic {}'.format(
85 b64encode('{}:{}'.format(
86 quote(self
.consumer_key
),
87 quote(self
.consumer_secret
)).encode('utf8')
95 class MissingCredentialsError(Exception):