-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreq_lib.py
63 lines (52 loc) · 1.98 KB
/
req_lib.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
#!/usr/bin/env python3
import requests
import json
from configs import Configs
class ReqLib:
def __init__(self):
self.configs = Configs()
'''
This function allows a user to make a request to
a certain endpoint, with the BASE_URL of
https://api.princeton.edu:443/active-directory/1.0.2
The parameters kwargs are keyword arguments. It
symbolizes a variable number of arguments
'''
def getJSON(self, endpoint, **kwargs):
req = requests.get(
self.configs.BASE_URL + endpoint,
params=kwargs if "kwargs" not in kwargs else kwargs["kwargs"],
headers={
"Authorization": "Bearer " + self.configs.ACCESS_TOKEN
},
)
text = req.text
# Check to see if the response failed due to invalid
# credentials
text = self._updateConfigs(text, endpoint, **kwargs)
return json.loads(text)
def _updateConfigs(self, text, endpoint, **kwargs):
if text.startswith("<ams:fault"):
self.configs._refreshToken(grant_type="client_credentials")
# Redo the request with the new access token
req = requests.get(
self.configs.BASE_URL + endpoint,
params=kwargs if "kwargs" not in kwargs else kwargs["kwargs"],
headers={
"Authorization": "Bearer " + self.configs.ACCESS_TOKEN
},
)
text = req.text
return text
def getXMLorTXT(self, endpoint, **kwargs):
req = requests.get(
self.configs.BASE_URL + endpoint,
params=kwargs if "kwargs" not in kwargs else kwargs["kwargs"],
headers={
"Authorization": "Bearer " + self.configs.ACCESS_TOKEN
},
)
# Check to see if the response failed due to invalid
# credentials
text = self._updateConfigs(req.text, endpoint, **kwargs)
return text