首页 > 其他 > 详细

flask restful接口开发之自定义序列化规则

时间:2021-06-06 16:22:20      阅读:10      评论:0      收藏:0      [点我收藏+]
 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)

 

flask restful接口开发之自定义序列化规则

原文:https://www.cnblogs.com/Liu928011/p/14855291.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!