-
Notifications
You must be signed in to change notification settings - Fork 6
/
apis.py
310 lines (255 loc) · 9.57 KB
/
apis.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import web
import json
from web import ctx
from web.contrib.template import render_jinja
import requests
from addons.get_CET import CET
from addons.calc_GPA import GPA
from addons.zfr import ZF, Login
from addons.redis2s import rds
from addons.mongo2s import init_mongo
from addons.data_factory import KbJson, get_score_dict
from addons import errors
from addons.autocache import redis_memoize
from addons.utils import incr_key
render = render_jinja('templates', encoding='utf-8')
API_TRIES_LIMIT = 1000 # 使用次数(次)
API_TIME_LIMIT = 3600 # 时间段(s) 即: 一小时内允许1000次请求(GET and POST)
urls = (
'/', 'APIDoc',
'/test', 'APITest',
'/checkcode.gif', 'CheckCode',
# user
'/user/login.json', 'UserLogin',
'/user/(score|timetable)/(\w+).json', 'UserRequest',
'/user/(score|timetable)/(\w+)/(raw?).json', 'UserRequest',
'/(score|timetable)/current_semester.json', "CurrentSemester",
'/(timetable?)/(current_semester?)/(raw?).json', "CurrentSemester",
'/score/(gpa|all|former_cet).json', 'GPAHandler',
)
class APIDoc:
""" API 文档 首页"""
def GET(self):
return ('<script src="https://gist.github.com'
'/zhwei/2c01aa053cc5ee3e45dc.js"></script>')
class BaseApiMixin(object):
""" Base Class of API
"""
def json_dumps(self, json_source):
return json.dumps(json_source, ensure_ascii=False)
def json_response(self, data=None, message="Success"):
""" 填入 status 信息 """
json_source = {
"status" : {
"code" : int(web.ctx.status[:3]),
"message" : message
},
}
if data: json_source.update({'data': data})
return self.json_dumps(json_source)
def json_request(self):
json_content = web.data()
return json.loads(json_content)
class APITest(BaseApiMixin):
def GET(self):
# ['status', 'realhome', 'homedomain', 'protocol', 'app_stack',
# 'ip', 'fullpath', 'headers', 'host', 'environ', 'env', 'home',
# 'homepath', 'output', 'path', 'query', 'method']
return web.ctx.environ["HTTP_ACCESS_TOKEN"]
class BaseGet(object):
""" 基类
默认GET返回UID
"""
def GET(self, category=None, item=None, raw=False):
try:
zf = ZF()
uid = zf.pre_login()
except errors.RequestError, e:
return self.json_response({}, message=e.value)
return self.json_response(data={"uid":uid})
class UserLogin(BaseApiMixin, BaseGet):
""" 验证类 登录请求 """
def POST(self):
try:
content = self.json_request()
except:
web.ctx.status = "400"
return self.json_response(message="data format wrong")
try:
zf = Login()
try:
if web.input(_method='get').nocode == "true":
uid = zf.no_code_login(content)
else: raise AttributeError
except AttributeError:
uid = content["uid"]
zf.login(uid, content)
return self.json_response(data={"uid": uid})
except KeyError:
web.ctx.status = "400"
return self.json_response(message="data format wrong")
except errors.PageError, e:
return self.json_response({}, message=e.value)
class CheckCode(BaseApiMixin):
""" 验证码链接 """
def GET(self):
try:
uid = web.input(_method='get').uid
except AttributeError:
return self.json_response({}, message='no UID')
web.header('Content-Type','image/gif')
zf = ZF()
return zf.get_checkcode(uid)
class UserRequest(BaseApiMixin):
""" 验证类: 处理全部请求 """
category_list = ('score', 'timetable')
item_list = ('current_semester', 'last_semester','all', 'gpa', 'former_cet')
def POST(self, category=None, item=None, raw=False):
if category not in self.category_list or item not in self.item_list:
raise web.notfound()
try:
content = self.json_request()
self.uid = content['uid']
except:
web.ctx.status = "400"
return self.json_response(message="data format wrong")
try:
self.xh = rds.hget(self.uid, "xh")
if category == "score":
if item == "former_cet":
cet = CET()
data = cet.get_cet_json(self.xh)
elif item == "gpa":
gpa = GPA(self.xh)
data = {"gpa": gpa.get_gpa()}
elif item == "all":
gpa = GPA(self.xh)
data = gpa.get_allscore_dict()
elif item == "current_semester":
zf = Login()
zf.init_after_login(self.uid, self.xh)
score = zf.get_score()
data = get_score_dict(score)
elif item == "last_semester":
zf = Login()
zf.init_after_login(self.uid, self.xh)
score = zf.get_last_score()
data = get_score_dict(score)
elif category == "timetable":
zf = Login()
zf.init_after_login(self.uid, self.xh)
if item == "current_semester":
timetable = zf.get_timetable()
elif item == "last_semester":
timetable = zf.get_last_timetable()
if raw:
data = {"raw": timetable}
else:
k = KbJson(timetable)
data_list = k.get_list()
data = data_list
return self.json_response(data)
except (AttributeError, TypeError, KeyError, requests.TooManyRedirects), e:
web.ctx.status = "401"
return self.json_response({}, message="Need Login")
except (errors.RequestError, errors.PageError), e:
return self.json_response({}, message=e.value)
class CurrentSemester(BaseApiMixin, BaseGet):
""" 处理对当前学期的查询 """
def POST(self, category=None, item=None, raw=False):
try:
content = self.json_request()
except:
web.ctx.status = "400"
return self.json_response(message="data format wrong")
try:
zf = Login()
try:
if web.input(_method='get').nocode == "true":
zf.no_code_login(content)
else: raise AttributeError
except AttributeError:
zf.login(content["uid"], content)
if category == "score":
score = zf.get_score()
data = get_score_dict(score)
elif category == "timetable":
timetable = zf.get_last_timetable()
if raw:
data = {"raw": timetable}
else:
k = KbJson(timetable)
data_list = k.get_list()
data = data_list
return self.json_response(data)
except errors.PageError, e:
return self.json_response({}, message=e.value)
except KeyError, e:
web.ctx.status = "400"
return self.json_response(message="KeyError: %s" % e)
class GPAHandler(BaseApiMixin):
""" 获取全部成绩或者学分绩点 """
def POST(self, category):
try:
content = self.json_request()
self.xh = content['xh']
except:
web.ctx.status = "400"
return self.json_response(message="data format wrong")
if category == "former_cet":
cet = CET()
data = cet.get_cet_json(self.xh)
else:
gpa = GPA(self.xh)
if category == "gpa":
data = {"gpa": gpa.get_gpa()}
elif category == "all":
data = gpa.get_allscore_dict()
return self.json_response(data)
def notfound():
"""404
"""
base = BaseApiMixin()
web.ctx.status = "404"
return web.notfound(base.json_response(message="Not Found"))
def internalerror():
"""500
"""
base = BaseApiMixin()
web.ctx.status = "500"
return web.internalerror(base.json_response(message="Internal Error"))
def limit_processor(handler):
@redis_memoize(10000, "developer")
def developer_list():
db = init_mongo()
return [d['token'] for d in db['developer'].find()]
base = BaseApiMixin()
if web.ctx.path not in ['/', '/checkcode.gif']:
try:
token = web.ctx.environ["HTTP_ACCESSTOKEN"]
if token in developer_list():
# times limit
# _key = "Token:{}".format(token)
_day_key = "Token:Day:{}".format(token)
_total_key = "Token:Total:{}".format(token)
# if incr_key(_key, API_TIME_LIMIT) < API_TRIES_LIMIT:
incr_key(_day_key, 3600*24) # day
incr_key(_total_key) # total
return handler()
# incr_key("Error:TriesLimit")
# return base.json_response(message="Tries Limit")
else:
raise KeyError
except KeyError:
web.ctx.status = "401"
incr_key("Error:NoAccessToken")
return base.json_response(message="No ACCESS_TOKEN SET")
else:
return handler()
app = web.application(urls, locals())
app.notfound = notfound
app.internalerror = internalerror
app.add_processor(limit_processor)