-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
66 lines (49 loc) · 2.15 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import base64
import urllib
import requests
class Api:
def __init__(self, consumer_key='', consumer_secret='', bearer_token=''):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.bearer_token = bearer_token
self.encode_credentials()
if not self.bearer_token:
self.request_bearer_token()
def make_request(self, url, params={}):
headers = {
'Authorization': 'Bearer {0}'.format(self.bearer_token)
}
return requests.get('https://api.twitter.com/{0}'.format(url),
headers=headers, params=params)
def encode_credentials(self):
encoded_key = urllib.urlencode({'': self.consumer_key})[1:]
encoded_secret = urllib.urlencode({'': self.consumer_secret})[1:]
credentials = '{0}:{1}'.format(encoded_key, encoded_secret)
self.encoded_credentials = base64.b64encode(credentials)
def request_bearer_token(self):
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic {0}'.format(self.encoded_credentials)
}
req = requests.post('https://api.twitter.com/oauth2/token',
data={'grant_type': 'client_credentials'},
headers=headers)
if req:
res = req.json()
if res['token_type'] == 'bearer':
self.bearer_token = res['access_token']
def invalidate_bearer_token(self):
headers = {
'Authorization': 'Basic {0}'.format(self.encoded_credentials)
}
req = requests.post('https://api.twitter.com/oauth2/invalidate_token',
data={'access_token': self.bearer_token},
headers=headers)
if req:
res = req.json()
if res['access_token'] == self.bearer_token:
self.bearer_token = ''
def get_user_timeline(self, params={}, **kwargs):
params.update(kwargs)
req = self.make_request('1.1/statuses/user_timeline.json', params)
return req.json() if req else []