]>
jfr.im git - z_archive/twitter.git/blob - twitter/oauth2.py
2 Visit the Twitter developer page and create a new application:
4 https://dev.twitter.com/apps/new
6 This will get you a CONSUMER_KEY and CONSUMER_SECRET.
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.
13 Finally, you can use the OAuth2 authenticator to connect to Twitter. In
14 code it all goes like this::
16 twitter = Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN))
18 # Now work with Twitter
19 twitter.search.tweets(q='keyword')
23 from __future__
import print_function
26 from urllib
.parse
import quote
, urlencode
28 from urllib
import quote
, urlencode
30 from base64
import b64encode
31 from .auth
import Auth
36 An OAuth2 application-only authenticator.
38 def __init__(self
, consumer_key
=None, consumer_secret
=None,
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.
45 self
.bearer_token
= None
46 self
.consumer_key
= None
47 self
.consumer_secret
= None
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
55 raise MissingCredentialsError(
56 'You must supply either a bearer token, or both a '
57 'consumer_key and a consumer_secret.')
59 def encode_params(self
, base_url
, method
, params
):
61 return urlencode(params
)
63 def generate_headers(self
):
66 b
'Authorization': 'Bearer {0}'.format(
67 self
.bearer_token
).encode('utf8')
70 elif self
.consumer_key
and self
.consumer_secret
:
73 b
'Content-Type': (b
'application/x-www-form-urlencoded;'
75 b
'Authorization': 'Basic {0}'.format(
76 b64encode('{0}:{1}'.format(
77 quote(self
.consumer_key
),
78 quote(self
.consumer_secret
)).encode('utf8')
84 raise MissingCredentialsError(
85 'You must supply either a bearer token, or both a '
86 'consumer_key and a consumer_secret.')
91 class MissingCredentialsError(Exception):