cms.py
1.98 KB
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
import requests
from settings import conf
from common.redis_cache import redis_handler as rh
from apps.doc.exceptions import CMSException
class CMS:
def __init__(self):
self.oauth_url = conf.CMS_OAUTH_URL
self.url = conf.CMS_URL
self.oauth_payload = {
'grant_type': 'client_credentials',
'client_id': conf.CMS_OAUTH_ID,
'client_secret': conf.CMS_OAUTH_SECRET,
'scope': conf.CMS_OAUTH_SCOPE
}
self.token_type = 'bearer'
self.token = None
self.token_key = 'access_token'
self.expires_key = 'expires_in'
self.token_type_key = 'token_type'
def update_token(self):
response = requests.post(self.oauth_url, data=self.oauth_payload, files=[], verify=False)
if response.status_code != 200:
raise CMSException('CMS Oauth response with code: {0}'.format(response.status_code))
token = response.json().get(self.token_key)
if not isinstance(token, str):
raise CMSException('CMS Oauth can not get token: {0}'.format(response.json()))
self.token = token
self.token_type = response.json().get(self.token_type_key, self.token_type)
expires = response.json().get(self.expires_key, 3600)
rh.set_cms_token(self.token, expires)
def get_token(self):
if self.token is None:
self.token = rh.get_cms_token()
if self.token is None:
self.update_token()
return self.token
def send(self, payload):
token = self.get_token()
headers = {
'Authorization': '{0} {1}'.format(self.token_type.capitalize(), token),
'Content-Type': 'application/json',
}
response = requests.post(self.url, headers=headers, json=payload, verify=False)
if response.status_code != 200:
raise CMSException('CMS Oauth response with code: {0}'.format(response.status_code))
return response.json()
cms = CMS()