]> jfr.im git - z_archive/twitter.git/blame - twitter/oauth2.py
add doc to send tweets with images in README + consolidate api.py/README
[z_archive/twitter.git] / twitter / oauth2.py
CommitLineData
e99a58f8
NS
1"""
2Visit the Twitter developer page and create a new application:
3
4 https://dev.twitter.com/apps/new
5
6This will get you a CONSUMER_KEY and CONSUMER_SECRET.
7
8Twitter only supports the application-only flow of OAuth2 for certain
9API endpoints. This OAuth2 authenticator only supports the application-only
10flow right now. If twitter supports OAuth2 for other endpoints, this
11authenticator may be modified as needed.
12
13Finally, you can use the OAuth2 authenticator to connect to Twitter. In
14code 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
23from __future__ import print_function
24
25try:
26 from urllib.parse import quote, urlencode
27except ImportError:
28 from urllib import quote, urlencode
29
30from base64 import b64encode
49e28bf1 31from .auth import Auth
e99a58f8
NS
32
33
34class 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
91class MissingCredentialsError(Exception):
92 pass