This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 262
/
webapi_utils.py
79 lines (66 loc) · 2.55 KB
/
webapi_utils.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import logging
import requests
from configloader import get_config
class WebApi(object):
def __init__(self):
self.session_pool = requests.Session()
def getApi(self, uri, params={}):
r""" Send a ``GET`` request to API server. Return response["data"] or []
:param uri: URI to request
:param params: Optional arguments ``request`` takes
:rtype: list
"""
params["key"] = get_config().WEBAPI_TOKEN
response = self.session_pool.get(
"%s/mod_mu/%s" % (get_config().WEBAPI_URL, uri),
params=params,
timeout=10,
)
if response.status_code != 200:
logging.error("Server error with status code: %i" %
response.status_code)
raise Exception('Server Error!')
try:
json_data = response.json()
except:
logging.error("Wrong data: %s" % response.text)
raise Exception('Server Error!')
if len(json_data) != 2:
logging.error("Wrong data: %s" % response.text)
raise Exception('Server Error!')
if json_data["ret"] == 0:
logging.error("Wrong data: %s" % json_data["data"])
raise Exception('Server Error!')
return json_data["data"]
def postApi(self, uri, params={}, json={}):
r""" Send a ``POST`` request to API server. Return response["data"] or []
:param uri: URI to request
:param params: Optional arguments ``request`` takes
:param json: Optional arguments ``json`` that ``request`` takes
:rtype: list
"""
params["key"] = get_config().WEBAPI_TOKEN
response = self.session_pool.post(
"%s/mod_mu/%s" % (get_config().WEBAPI_URL, uri),
params=params,
json=json,
timeout=10,
)
if response.status_code != 200:
logging.error("Server error with status code: %i" %
response.status_code)
raise Exception('Server Error!')
try:
json_data = response.json()
except:
logging.error("Wrong data: %s" % response.text)
raise Exception('Server Error!')
if len(json_data) != 2:
logging.error("Wrong data: %s" % response.text)
raise Exception('Server Error!')
if json_data["ret"] == 0:
logging.error("Wrong data: %s" % json_data["data"])
raise Exception('Server Error!')
return json_data["data"]