其他分享
首页 > 其他分享> > restful

restful

作者:互联网

flask-restful

1.提供了RequestParser类,可以帮助我们校验和转换请求数据,它设计成提供简单并且统一的访问Flask.request对象里的任何变量的入口
请求解析:
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('title', type=str, location=['form', 'json'], required=True, help='标题是必田')
        parse.add_argument('praise', type=int, location=['form', 'json'], default=0, help='请输入合法值')
        parse.add_argument('stock', type=int, location=['form', 'json'], default=0, help='请输入合法值')

        args = parse.parse_args()

        good = Goods(**args)

        db.session.add(good)
        try:
            db.session.commit()
        except SQLAlchemyError as e:
            print(e)
            return {
                       'msg': '添加失败'
                   }, 500

        return {
                   'id': good.id,
                   'title': good.title,
                   'praise': good.praise,
                   'stock': good.stock,
               }, 201
class MajorView(Resource):
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('name', type=str, location=['form', 'json'], required=True, help='请输入正确的专业名')

        name = parse.parse_args().get('name')

        major = Major(name=name)
        db.session.add(major)
        try:
            db.session.commit()
        except:
            return {'msg': '添加失败'}, 500
        return {
                   'id': major.id,
                   'name': major.name,
               }, 201
响应:
序列化数据:Flask-RESTful提供了marshal工具,可以将数据序列化为特定格式的字典数据,作为视图的返回值
from flask_restful import fields
resource_fields = {
    'name': fields.String,
    'age': fields.Integer,
}

导入装饰器和序列化字段

from flask_restful import marshal_with
from field import resource_fields

装饰器装饰视图类

class Index(Resource):
    @marshal_with(resource_fields)
    def get(self, **kwargs):
        user = User('Jeremy', 18, '123456')
        return user
from flask_restful import fields
resource_fields = {
    'name': fields.String,
    'age': fields.Integer,
}

导入marshal方法和序列化字段

from flask_restful import marshal
from field import resource_fields

marshal方法序列化结果

class Index(Resource):
    def get(self, **kwargs):
        user = User('Jeremy', 18, '123456')
        # marshal()方法直接序列化数据
        	# user: 要序列化的数据
            # resource_fields: 要序列化的字段
        return marshal(user, resource_fields)

标签:name,fields,args,parse,序列化,restful,marshal
来源: https://www.cnblogs.com/history0403/p/14856647.html