ecm.py
3.22 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import base64
import requests
from common.redis_cache import redis_handler as rh
from settings import conf
from apps.doc.exceptions import ECMException
class ECM:
def __init__(self):
self.oauth_token = None
self.username = conf.ECM_USER
self.pwd = conf.ECM_PWD
self.oauth_url = conf.ECM_OAUTH_URL
self.download_url = conf.ECM_DOWNLOAD_URL
self.oauth_headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
self.oauth_payload = {
'grant_type': 'client_credentials',
'client_id': conf.ECM_OAUTH_ID,
'client_secret': conf.ECM_OAUTH_SECRET,
}
self.token_key = 'access_token'
self.token_type = 'Bearer'
self.token_type_key = 'token_type'
self.expires_key = 'expires_in'
def update_oauth_token(self):
response = requests.post(self.oauth_url, headers=self.oauth_headers, data=self.oauth_payload, verify=False)
if response.status_code != 200:
raise ECMException('ECM Oauth response with code: {0}'.format(response.status_code))
token = response.json().get(self.token_key)
if not isinstance(token, str):
raise ECMException('ECM Oauth can not get token: {0}'.format(response.json()))
self.oauth_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_ecm_token(self.oauth_token, expires)
def get_oauth_token(self):
if self.oauth_token is None:
# redis获取token
self.oauth_token = rh.get_ecm_token()
if self.oauth_token is None:
self.update_oauth_token()
return self.oauth_token
def download(self, save_path, doc_base, doc_type, object_id):
download_headers = {
'Authorization': '{0} {1}'.format(self.token_type, self.get_oauth_token())
}
download_json = {
"userName": self.username,
"password": self.pwd,
"docbase": doc_base,
"documentType": doc_type,
"objectId": object_id,
}
response = requests.post(self.download_url, headers=download_headers, json=download_json, verify=False)
if response.status_code != 200:
raise ECMException('ECM download response with code: {0}'.format(response.status_code))
base64_data = response.json().get('Envelope', {}).get('Body', {}).get('getResponse', {}).get('return', {}).get(
'DataObjects', {}).get('Contents', {}).get('Value')
if not isinstance(base64_data, str):
raise ECMException('ECM download failed: {0}'.format(response.json()))
with open(save_path, "wb") as fh:
fh.write(base64.b64decode(base64_data.encode()))
def upload(self):
{
"username": "fanliubing",
"password": "Bmwecm123456&api1",
"docbase": "SF5_CN",
"documentType": "acceptance",
"object_name": "JoeMyPDF202109061529.pdf",
"folder": "/Wholesale/Operations/Audits",
"format": "pdf",
"b_application_no": "",
"file_base64_content": "",
}