This repository was archived by the owner on Jul 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
171 lines (129 loc) · 4.87 KB
/
api.py
File metadata and controls
171 lines (129 loc) · 4.87 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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""API封装"""
from datetime import datetime
from typing import Any, Dict, List, Tuple
import requests
# BASE_URL = 'https://acss.jnn.icu/api' # 基础 API URL (停止维护)
BASE_URL = 'http://127.0.0.1:8000' # 本地测试 URL
TOKEN = ''
class ApiError(BaseException):
"""API返回值为-1时抛出该异常
服务端抛出错误信息时,raise本异常,
外侧调用者捕获该异常并决定是否打印异常信息。
抛出方法:
```
if resp['code'] == -1:
raise ApiError(resp['message'])
```
处理方法:
```
try:
some_api()
except ApiError as e:
some_toast(str(e)).show()
```
"""
async def api_post(path: str, json: Dict) -> Dict[str, Any] | None:
"""POST 请求封装
Args:
path (str): BASE_URL 后的相对路径
json (Dict): 字典,会被转换为JSON字符串置于请求体中
Raises:
ApiError: 响应码为-1的异常,包含错误信息
Returns:
Dict[str, Any] | None: 响应中的 data 字段,可能为 None
"""
url = BASE_URL + path
try:
if len(TOKEN) > 0:
header = {'Authorization': f'Bearer {TOKEN}'}
resp: dict = requests.post(url=url, json=json, headers=header).json()
else:
resp: dict = requests.post(url=url, json=json).json()
except requests.exceptions.ConnectTimeout as e:
raise ApiError('连接超时') from e
except requests.exceptions.ConnectionError as e:
raise ApiError('连接错误') from e
except requests.exceptions.ReadTimeout as e:
raise ApiError('数据读取超时') from e
except requests.exceptions.HTTPError as e:
raise ApiError('Http错误') from e
except BaseException as e:
raise ApiError('网络错误') from e
if resp['code'] == -1:
raise ApiError(resp['message'])
return resp.get('data')
async def api_get(path: str) -> Dict[str, Any] | None:
"""GET 请求封装
Args:
path (str): BASE_URL 后的相对路径
Raises:
ApiError: 响应码为-1的异常,包含错误信息
Returns:
Dict[str, Any] | None: 响应中的 data 字段,可能为 None
"""
url = BASE_URL + path
try:
if len(TOKEN) > 0:
header = {'Authorization': f'Bearer {TOKEN}'}
resp: dict = requests.get(url=url, headers=header).json()
else:
resp: dict = requests.get(url=url).json()
except requests.exceptions.ConnectTimeout as e:
raise ApiError('连接超时') from e
except requests.exceptions.ConnectionError as e:
raise ApiError('连接错误') from e
except requests.exceptions.ReadTimeout as e:
raise ApiError('数据读取超时') from e
except requests.exceptions.HTTPError as e:
raise ApiError('Http错误') from e
except BaseException as e:
raise ApiError('网络错误') from e
if resp['code'] == -1:
raise ApiError(resp['message'])
return resp.get('data')
async def login(username: str, password: str) -> Dict[str, Any]:
data = await api_post('/login', json={'username': username, 'password': password})
return data['token'], data['is_admin']
async def time() -> Tuple[datetime, int]:
data = await api_get('/time')
return data['datetime'], data['timestamp']
async def register(username: str, password: str) -> None:
await api_post('/user/register', json={
'username': username,
'password': password,
're_password': password
})
async def submit_charging_request(charge_mode: str, require_amount: str, battery_size: str) -> None:
await api_post('/user/submit_charging_request', json={
'charge_mode': charge_mode,
'require_amount': require_amount,
'battery_size': battery_size
})
async def edit_charging_request(charge_mode: str, require_amount: str) -> None:
await api_post('/user/edit_charging_request', json={
'charge_mode': charge_mode,
'require_amount': require_amount
})
async def end_charging_request() -> None:
await api_get('/user/end_charging_request')
async def query_order_detail() -> List[Dict[str, Any]]:
data = await api_get('/user/query_order_detail')
return data
async def preview_queue() -> Dict[str, Any]:
data = await api_get('/user/preview_queue')
return data
async def query_all_piles_stat() -> Dict[str, Any]:
data = await api_get('/admin/query_all_piles_stat')
return data
async def admin_status_report() -> List[Dict[str, Any]]:
data = await api_get('/admin/query_report')
return data
async def admin_query_queue() -> List[Dict[str, Any]]:
data = await api_get('/admin/query_queue')
return data
async def update_pile_stat(pile_id: str, status: str) -> None:
data = await api_post('/admin/update_pile', json={
'pile_id': pile_id,
'status': status
})
return data