-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtemplate.py
153 lines (131 loc) · 5.43 KB
/
template.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import requests
import json
import os
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter
class HttpMethod:
"""
HttpMethod will have methods to send
GET, POST, PATCH, PUT, DELETE request to the initalized url
"""
def __init__(self, extension, session, **kwargs):
self.url = "https://api.intra.42.fr{}".format(extension)
self.filter = kwargs["filter"] if "filter" in kwargs else {}
self.page = kwargs["pages"] if "pages" in kwargs else {'size':100, 'number':1}
self.sort = kwargs["sort"] if "sort" in kwargs else ""
self.range = kwargs["range"] if "range" in kwargs else {}
self.session = session
def ParseParams(self):
filter_query = "&".join([f"filter[{key}]={value}" for key, value in self.filter.items()]) if self.filter else ""
page_query = "&".join([f"page[{key}]={value}" for key, value in self.page.items()]) if self.page else ""
range_query = "&".join([f"range[{key}]={value}" for key, value in self.range.items()]) if self.range else ""
result = "&".join([query for query in [filter_query, page_query, range_query] if query != ""])
if self.sort:
if result:
result += f"&sort={self.sort}"
else:
result = f"sort={self.sort}"
return f"?{result}" if result else ""
def Get(self):
"""
return json
"""
response = self.session.get(self.url + self.ParseParams())
response.raise_for_status()
if self.page and "number" in self.page: self.page['number'] += 1
return json.loads(response.text)
def Post(self, data):
"""
return response Object
"""
response = self.session.post(self.url, json=data)
try:
response.raise_for_status()
except:
raise Exception(f"[{response.status_code}] {response.content}")
return response
def Patch(self, data):
"""
return response Object
"""
response = self.session.patch(self.url, json=data)
try:
response.raise_for_status()
except:
raise Exception(f"[{response.status_code}] {response.content}")
return response
def Put(self, data):
"""
return response Object
"""
response = self.session.put(self.url, json=data)
try:
response.raise_for_status()
except:
raise Exception(f"[{response.status_code}] {response.content}")
return response
def Delete(self):
"""
return response Object
"""
response = self.session.delete(self.url)
try:
response.raise_for_status()
except:
raise Exception(f"[{response.status_code}] {response.content}")
return response
class FtApi:
def __init__(self, uid=None, secret=None, code=None, redirect=None, bearer=None, scope=None):
self.uid = uid if uid is not None else os.environ['UID42'] if bearer is None else ""
self.secret = secret if secret is not None else os.environ['SECRET42'] if bearer is None else ""
self.code = code
self.redirect = redirect
self.bearer = bearer
self.scope = scope if scope is not None else "public projects profile elearning tig forum"
if self.bearer is None:
try:
self.bearer = self.GetBearer()
except Exception as e:
raise Exception(e)
self.session = requests.Session()
self.session.headers.update({'Authorization': 'Bearer {}'.format(self.bearer)})
def FastInit(self):
self.__init__(os.environ['UID42'], os.environ['SECRET42'])
def GetBearer(self):
"""
Makes a call to get Bearer with your crendentials
return: string
"""
if self.code:
payload = {'grant_type':'authorization_code', 'client_id': self.uid,
'client_secret': self.secret, 'code':self.code, 'redirect_uri':self.redirect}
else:
payload = {'grant_type':'client_credentials', 'client_id': self.uid, "scope": self.scope,
'client_secret': self.secret}
try:
response = requests.post("https://api.intra.42.fr/oauth/token", data=payload)
if response.status_code != 200:
raise Exception("wrong status_code:{}".format(response.status_code))
parsed_response = json.loads(response.content.decode('utf-8'))
except Exception as e:
raise Exception(e)
return parsed_response['access_token']
def ReloadBearer(self):
"""
Use this method in case 'The access token expired'
"""
self.bearer = self.GetBearer()
self.session = requests.Session()
self.session.headers.update({'Authorization': 'Bearer {}'.format(self.bearer)})
def RawEndpoint(self, endpoint, **kwargs):
"""
parameter : string
return : HttpMethod
Create a HttpMethod with passed parameter as the endpoint for "https://api.intra.42.fr/"
example :"/v2/users?filter[pool_year]=2019&page[size]=100&page[number]=3"
"""
return HttpMethod(endpoint, self.session, **kwargs)
def ColorizeJsonOutput(self, jsonObject):
jsonStr = json.dumps(jsonObject, indent=4, sort_keys=True)
print(highlight(jsonStr, JsonLexer(), TerminalFormatter()))