-
Notifications
You must be signed in to change notification settings - Fork 0
/
restful_apis.py
429 lines (408 loc) · 16.1 KB
/
restful_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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#!/usr/bin/python
# -*- coding:utf-8 -*-
from flask import Flask, request, abort
from flask.ext.restful import Resource, Api, reqparse, fields, marshal_with
from models import Student, Course, Employ
from MySQLdb import IntegrityError, OperationalError
import sys
sys.path.append('/home/czw/MySimpleWeb/transwarp')
import db
import datetime
app = Flask(__name__)
api = Api(app)
def sortby(datas, sort_by, order):
#升序
if order == 'asc':
datas = sorted(datas, lambda x,y: cmp(x[sort_by], y[sort_by]))
#降序
if order == 'desc':
datas = sorted(datas, lambda x,y: cmp(y[sort_by], x[sort_by]))
return datas
class StudentAdd(Resource):
"""
获取所有学生数据或者新增一数据.
curl http://localhost:port/students
"""
def get(self):
"""
返回列表
"""
datas = Student.find_all()
#判断是否为空
if datas != []:
#datetime.date转换为str,使得可以jsonify
for data in datas:
data['birthdate'] = datetime.datetime.strftime(data['birthdate'], '%Y%m%d')
#检查是否需要排序
sort_by = request.args.get('sortby')
order = request.args.get('order', 'asc')
if sort_by:
return sortby(datas, sort_by, order),200
return datas, 200
else:
return {'error': "has no student data"}, 404
def post(self):
"""
新增数据
"""
parser = reqparse.RequestParser()
parser.add_argument('sid', type=int)
parser.add_argument('sname', type=str)
parser.add_argument('sex', type=str)
parser.add_argument('birthplace', type=str)
parser.add_argument('birthdate', type=str)
parser.add_argument('department', type=str)
parser.add_argument('sclass', type=str)
args = parser.parse_args()
#判断输入完整性
for key,value in args.iteritems():
if value is None:
return {'error': "Please input field: %s" % key }, 400
stu = Student(**args)
try:
insert_row = stu.insert()
#判断是否插入成功
if insert_row == 1:
return stu, 201
except IntegrityError ,e:
#insert duplicate primary_key entry
if e[0] == 1062:
return {'primary error': e[1]}, 400
except Exception,e:
return {'error': e[1]}, 400
class StudentResource(Resource):
"""
查询/修改/删除一数据.
curl http://localhost:port/students/sid
"""
def get(self, sid):
"""
获取一指定sid数据,Student表主键为sid
"""
data = Student.get({'sid':sid})
if data is not None:
#datetime.date转换为str,使得可以jsonify
data['birthdate'] = datetime.datetime.strftime(data['birthdate'], '%Y%m%d')
return data,200
else:
return {'error': "has no student data with sid: %s" % sid},404
def put(self, sid):
"""
用于修改sid对应的数据行, 表单只需填写需要修改的数据项即可
"""
parser = reqparse.RequestParser()
parser.add_argument('sid', type=int)
parser.add_argument('sname', type=str)
parser.add_argument('sex', type=str)
parser.add_argument('birthplace', type=str)
parser.add_argument('birthdate', type=str)
parser.add_argument('department', type=str)
parser.add_argument('sclass', type=str)
args = parser.parse_args()
ModifyStudent = Student.get({'sid': sid})
#判断是否存在数据
if ModifyStudent is None:
return {'error' : "has no student data with sid: %s for modify(put), please send post request to create first" % sid}, 404
#若表单给出sid,此sid与url对应不同报错
if args['sid'] is not None and args['sid'] != sid:
return {'error' : "url's(put) sid(%s) is not equal to form sid(%s)" % (sid, args['sid'])},400
ModifyStudent['birthdate'] = datetime.datetime.strftime(ModifyStudent['birthdate'], '%Y%m%d')
for key, value in args.iteritems():
if value is not None:
ModifyStudent[key] = value
try:
update_row = ModifyStudent.update()
if update_row == 1:
return ModifyStudent,201
except Exception,e:
return {'error', e[1]},400
def delete(self, sid):
"""
删除sid对应数据行
"""
OldStudent = Student.get({'sid':sid})
#判断是否有sid对应数据
if OldStudent is None:
return {'error': "has no student data with sid: %s for deleted" % sid},404
try:
delete_row = OldStudent.delete()
if delete_row == 1:
return { 'success' : 'success delete data with sid:%s' % sid},204
except IntegrityError,e:
if e[0] == 1451:
return {'foreign error':e[1]},400 #外键约束
return {'error', e[1]},400
except Exception,e:
return {'error':e[1]},400
class CourseAdd(Resource):
"""
查看/新增课程
curl http://localhost:port/courses
"""
def get(self):
datas = Course.find_all()
if datas != []:
sort_by = request.args.get('sortby')
order = request.args.get('order', 'asc')
if sort_by:
return sortby(datas, sort_by, order),200
return datas,200
else:
return {'error': "has no course data"},404
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('cid', type=str)
parser.add_argument('cname', type=str)
parser.add_argument('chours', type=int)
parser.add_argument('credit', type=float)
parser.add_argument('precid', type=str)
args = parser.parse_args()
for key,value in args.iteritems():
if key == 'precid':
continue
if value is None:
return {'error':"Please input field: %s" % key},400
course = Course(**args)
try:
insert_row = course.insert()
if insert_row == 1:
return course,201
except IntegrityError ,e:
#insert duplicate primary_key entry
if e[0] == 1062:
return {'primary error': e[1]},400
except Exception,e:
return {'error': e[1]},400
class CourseResource(Resource):
def get(self, cid):
"""
获取一指定cid数据,Course表主键为cid
"""
data = Course.get({'cid':cid})
if data is not None:
return data,200
else:
return {'error': "has no course data with cid: %s" % cid},404
def put(self, cid):
"""
用于修改cid对应的数据行, 表单只需填写需要修改的数据项即可
"""
parser = reqparse.RequestParser()
parser.add_argument('cid', type=str)
parser.add_argument('cname', type=str)
parser.add_argument('chours', type=int)
parser.add_argument('credit', type=float)
parser.add_argument('precid', type=str)
args = parser.parse_args()
ModifyCourse = Course.get({'cid': cid})
#判断是否存在数据
if ModifyCourse is None:
return {'error' : "has no course data with cid: %s for modify(put), please send post request to create first" % cid}, 404
#若表单给出cid,此cid与url对应不同报错
if args['cid'] is not None and args['cid'] != cid:
return {'error' : "url's(put) cid(%s) is not equal to form cid(%s)" % (cid, args['cid'])},400
for key, value in args.iteritems():
if value is not None:
ModifyCourse[key] = value
try:
update_row = ModifyCourse.update()
if update_row == 1:
return ModifyCourse,201
except Exception,e:
return {'error', e[1]},400
def delete(self, cid):
"""
删除cid对应数据行
"""
OldCourse = Course.get({'cid':cid})
#判断是否有sid对应数据
if OldCourse is None:
return {'error': "has no course data with cid:%s for deleted" % cid},404
try:
delete_row = OldCourse.delete()
if delete_row == 1:
return { 'success' : 'success delete data with cid:%s' % cid},204
except IntegrityError,e:
if e[0] == 1451:
return {'foreign error':e[1]},400 #外键约束
return {'error':e[1]},400
except Exception,e:
return {'error':e[1]},400
class EmployAdd(Resource):
"""
获取所有数据或者新增一数据.
curl http://localhost:port/employs
"""
def get(self):
"""
返回列表
"""
filter_course = request.args.get('course')
if filter_course:
datas = Employ.find_by('where cname="%s"' % filter_course)
else:
datas = Employ.find_all()
#判断是否为空
if datas != []:
sort_by = request.args.get('sortby')
order = request.args.get('order', 'asc')
if sort_by:
return sortby(datas, sort_by, order),200
return datas,200
else:
return {'error': "has no student data"},404
def post(self):
"""
新增数据
"""
parser = reqparse.RequestParser()
parser.add_argument('sid', type=int)
parser.add_argument('cid', type=str)
parser.add_argument('garde', type=int)
#parser.add_argument('sname', type=str)
#parser.add_argument('cname', type=str)
args = parser.parse_args()
#判断输入完整性
for key,value in args.iteritems():
if value is None:
return {'error': "Please input field: %s" % key },400
try:
sname = Student.get({'sid': args['sid']})['sname']
sclass = Student.get({'sid': args['sid']})['sclass']
cname = Course.get({'cid': args['cid']})['cname']
args['sname']=sname
args['cname']=cname
args['sclass']=sclass
except Exception,e:
return {'error': 'has no sid/cid data'},400
employ = Employ(**args)
try:
insert_row = employ.insert()
print insert_row
#判断是否插入成功
if insert_row == 1:
return employ,201
except IntegrityError ,e:
#insert duplicate primary_key entry
if e[0] == 1062:
return {'primary error': e[1]},400
#外键约束
if e[0] == 1452:
return {'foreign error': e[1]},400
return {'error': e[1]},400
except Exception,e:
return {'error': e[1]},400
class EmployResource(Resource):
"""
查询/修改/删除一数据.
curl http://localhost:port/employ/sid
curl http://localhost:port/employ/cid
curl http://localhost:port/employ/sid/cid
"""
def get(self, sid=None, cid=None):
"""
获取一指定sid/cid数据
"""
#'usage': 'curl http://localhost:port/employ/sid/cid'指定sidcid返回单独一数据
if sid is not None and cid is not None:
data = Employ.get({'sid':sid, 'cid':cid})
if data is not None:
return data,200
else:
return {'error': "has no employ data with sid:%s and cid:%s" % (sid, cid)},404
#'usage': 'curl http://localhost:port/employ/sid'指定sid,返回list
elif sid is not None and cid is None:
datas = Employ.find_by('where sid="%s"' % sid)
if datas != []:
#新增学习平均分和总分
total_garde = 0
for data in datas:
total_garde += data['garde']
avg_garde = total_garde/len(datas)
datas.append({'total_garde': total_garde})
datas.append({'avg_garde': avg_garde})
return datas,200
else:
return {'error': "has no employ data with sid: %s" % sid},404
#'usage': 'curl http://localhost:port/employ/cid'指定cid,返回list
elif sid is None and cid is not None:
datas = Employ.find_by('where cid="%s"' % cid)
if datas != []:
#排序
max_garde = []
datas = sortby(datas, 'garde', 'asc')
max = datas[-1]['garde']
for i in range(1,len(datas)+1):
if datas[-i]['garde'] == max:
max_garde.append(datas[-i])
continue
break
#max_garde.append(datas[-1])
#单科平均分
total_garde = 0
for data in datas:
total_garde += data['garde']
avg_garde = total_garde/len(datas)
datas.append({'avg_garde': avg_garde})
datas.append({'max_garde': max_garde})
return datas, 200
else:
return {'error': "has no employ data with cid: %s" % cid},404
def put(self, sid=None, cid=None):
"""
用于修改sid cid对应的数据行, 表单只需填写需要修改的数据项即可
"""
if sid is None or cid is None:
return {'usage': "curl http://localhost:port/employ/sid/cid. Please input sid and cid both."},400
parser = reqparse.RequestParser()
parser.add_argument('sid', type=int)
parser.add_argument('cid', type=str)
parser.add_argument('garde', type=int)
parser.add_argument('sname', type=str)
parser.add_argument('cname', type=str)
parser.add_argument('sclass', type=str)
args = parser.parse_args()
ModifyEmploy = Employ.get({'sid': sid, 'cid': cid})
#判断是否存在数据
if ModifyEmploy is None:
return {'error' : "has no employ data with sid:%s and cid:%s for modify(put), please send post request to create first" % (sid, cid)},404
#若表单给出sid/cid,此sid/cid与url对应不同,报错
if args['sid'] is not None and args['sid'] != sid:
return {'error' : "url's(put) sid(%s) is not equal to form sid(%s)" % (sid, args['sid'])},400
if args['cid'] is not None and args['cid'] != cid:
return {'error' : "url's(put) cid(%s) is not equal to form cid(%s)" % (cid, args['cid'])},400
for key, value in args.iteritems():
if value is not None:
ModifyEmploy[key] = value
try:
update_row = ModifyEmploy.update()
if update_row == 1:
return ModifyEmploy,201
except Exception,e:
return {'error', e[1]},400
def delete(self, sid=None, cid=None):
"""
删除sid对应数据行
"""
if sid is None or cid is None:
return {'usage': "curl http://localhost:port/employ/sid/cid. Please input sid and cid both."},400
OldEmploy = Employ.get({'sid':sid, 'cid':cid})
#判断是否有sid对应数据
if OldEmploy is None:
return {'error': "has no employ data with sid:%s and cid:%s for deleted" % (sid, cid)}, 404
try:
delete_row = OldEmploy.delete()
if delete_row == 1:
return {'success': "success delete data with sid:%s and cid:%s" % (sid, cid)}, 204
except Exception,e:
return {'error':e[1]},400
api.add_resource(StudentAdd, '/api/students')
api.add_resource(StudentResource, '/api/student/<int:sid>')
api.add_resource(CourseAdd, '/api/courses')
api.add_resource(CourseResource, '/api/course/<string:cid>')
api.add_resource(EmployAdd, '/api/employs')
api.add_resource(EmployResource, '/api/employ/<int:sid>/<string:cid>', '/api/employ/<int:sid>', '/api/employ/<string:cid>')
if __name__ == '__main__':
db.create_engine('root', 'password', 'university')
with db.connection():
app.run(host='0.0.0.0')