1 from flask_restful import Resource 2 from flask import jsonify, request 3 4 class BaseViewSet(Resource): 5 MODEL = None 6 def __init__(self): 7 self.result = { 8 ‘version‘: ‘v1.0‘, 9 ‘code‘: 200, 10 ‘data‘: [] 11 } 12 13 # 序列化 14 def serializer(self, obj_list): 15 result = [obj.__dict__ for obj in obj_list] 16 for res in result: 17 res.pop(‘_sa_instance_state‘) 18 self.result[‘data‘] = result 19 return jsonify(self.result) 20 21 # 当没有找到符合条件时返回的信息 22 def NotFound(self): 23 self.result[‘code‘] = 404 24 self.result[‘data‘].append(‘not found‘) 25 return jsonify(self.result) 26 27 # 发生异常时 28 def exception(self, error): 29 self.result[‘code‘] = 500 30 self.result[‘data‘].append(error) 31 return jsonify(self.result) 32 33 def get(self, id=None): 34 if id: #通过id单个查询 35 obj = self.MODEL.query.get(id) 36 if obj: 37 return self.serializer([obj]) 38 else: 39 return self.NotFound() 40 else: #通过条件批量查询 41 data = request.args 42 try: 43 obj_list = self.MODEL.query.filter_by(**data) 44 except Exception as error: 45 return self.exception(str(error)) 46 else: 47 return self.serializer(obj_list) 48 49 def post(self): 50 data = request.form 51 obj = self.MODEL(**data) 52 try: 53 obj.save() #提交的数据同步到数据库 54 except Exception as error: 55 return self.exception(str(error)) 56 else: 57 new_obj = self.MODEL.query.get(obj.id) 58 return self.serializer([new_obj]) 59 60 def put(self, id): 61 data = request.form 62 obj = self.MODEL.query.get(id) 63 if obj: 64 for k, v in data.items(): 65 setattr(obj, k, v) #修改数据 66 try: 67 obj.update() #同步到数据库 68 except Exception as error: 69 return self.exception(str(error)) 70 else: 71 new_obj = self.MODEL.query.get(obj.id) 72 return self.serializer([new_obj]) 73 else: 74 return self.NotFound() 75 76 def delete(self, id): 77 obj = self.MODEL.query.get(id) 78 if obj: 79 try: 80 obj.delete() 81 except Exception as error: 82 return self.exception(str(error)) 83 else: 84 return self.NotFound() 85 return jsonify(self.result)
原文:https://www.cnblogs.com/Liu928011/p/14855291.html