Flask-Restful

1、Restful规范

https://blog.csdn.net/T_I_A_N_/article/details/99471163

2、Flask-Restful插件的使用

1. 从flask_restful中导入Api,来创建一个api对象。

api = Api(app)

2. 写一个视图函数,让他继承自Resource,然后在这个里面,使用你想要的请求方式来定义相应的方法,比如你想要将这个视图只能采用`post`请求,那么就定义一个post方法。

class LoginView(Resource):
    def post(self):
        return {"username": "tian"}

    def get(self):
        return '666'

3. 使用api.add_resource来添加视图与url。

api.add_resource(LoginView, '/login/')

 

3、Flask-Restful参数验证

Flask-Restful插件提供了类似WTForms来验证提交的数据是否合法的包,叫做reqparse

from flask_restful import Api, Resource, reqparse, inputs

class LoginView(Resource):
    def post(self):
        from datetime import date
        parser = reqparse.RequestParser()  # 参数验证
        #add_argument可以指定这个字段的名字,这个字段的数据类型等。
        parser.add_argument('birthday', type=inputs.date, help='生日字段验证错误!') 
        parser.add_argument('telphone',type=inputs.regex(r'1[3578]\d{9}'))
        parser.add_argument('home_page',type=inputs.url,help='个人中心链接验证错误!')
        parser.add_argument('username',type=str,help='用户名验证错误!',required=True)
        parser.add_argument('password',type=str,help='密码验证错误!')
        parser.add_argument('age',type=int,help='年龄验证错误!')
        parser.add_argument('gender',type=str,choices=['male','female','secret'])
        args = parser.parse_args()  # 获取提交的数据
        return {"username": "tian"}

    def get(self):
        return '666'


api.add_resource(LoginView, '/login/')

参数说明

1. default:默认值,如果这个参数没有值,那么将使用这个参数指定的值。
2. required:是否必须。默认为False,如果设置为True,那么这个参数就必须提交上来。
3. type:这个参数的数据类型,如果指定,那么将使用指定的数据类型来强制转换提交上来的值。
4. choices:选项。提交上来的值只有满足这个选项中的值才符合验证通过,否则验证不通过。
5. help:错误信息。如果验证失败后,将会使用这个参数指定的值作为错误信息。
6. trim:是否要去掉前后的空格。

其中的type,可以使用python自带的一些数据类型,也可以使用flask_restful.inputs下的一些特定的数据类型来强制转换。比如一些常用的:
1. url:会判断这个参数的值是否是一个url,如果不是,那么就会抛出异常。
2. regex:正则表达式。
3. date:将这个字符串转换为datetime.date数据类型。如果转换不成功,则会抛出一个异常。

4、标准化返回参数

①示例

对于一个视图函数,你可以指定好一些字段用于返回。以后可以使用ORM模型或者自定义的模型的时候,他会自动的获取模型中的相应的字段,生成json数据,然后再返回给客户端。这其中需要导入flask_restful.marshal_with装饰器。并且需要写一个字典,来指示需要返回的字段,以及该字段的数据类型。

from flask_restful import Api, Resource, fields, marshal_with
from flask import Flask


app = Flask(__name__)
api = Api(app)

class ProfileView(Resource):
    resource_fields = {
        'username': fields.String,
        'age': fields.Integer,
        'school': fields.String
    }

    @marshal_with(resource_fields)
    def get(self,user_id):
        user = User.query.get(user_id)
        return user

api.add_resource(ProfileView,'/user/',endpoint='user')

在get方法中,返回user的时候,flask_restful会自动的读取user模型上的username以及age还有school属性。组装成一个json格式的字符串返回给客户端。

②重命名属性

想要显示的字段和建表的字段不一致。

    resource_fields = {
        'aritlce_title': fields.String(attribute='title'),
}

③复杂结构

有时候想要在返回的数据格式中,形成比较复杂的结构。那么可以使用一些特殊的字段来实现。比如要在一个字段中放置一个列表,那么可以使用fields.List,比如在一个字段下面又是一个字典,那么可以使用fields.Nested

class ArticleView(Resource):
    resource_fields = {
        'aritlce_title': fields.String(attribute='title'),
        'content': fields.String,
        # 嵌套
        'author': fields.Nested({
            'username': fields.String,
            'email': fields.String
        }),
        # 列表展示
        'tags': fields.List(fields.Nested({
            'id': fields.Integer,
            'name': fields.String
        })),
        'read_count': fields.Integer(default=80)
    }

    @marshal_with(resource_fields)
    def get(self, article_id):
        article = Article.query.get(article_id)
        return article

api.add_resource(ArticleView, '/<article_id>/', endpoint='article')

5、注意事项

1. 在蓝图中,如果使用flask-restful,那么在创建Api对象的时候,就不要再使用app了,而是使用蓝图
2. 如果在flask-restful的视图中想要返回`html`代码,或者是模版,那么就应该使用api.representation这个装饰器来定义一个函数,在这个函数中,应该对html代码进行一个封装,再返回。

# 这个代码是经过修改后的,能支持html和json。。restful只返回json格式数据
@api.representation('text/html')
def output_html(data, code, headers):
    if isinstance(data, str):
        # 在representation装饰的函数中,必须返回一个Response对象
        resp = make_response(data)
        return resp
    else:
        return Response(json.dumps(data), mimetype='application/json')

 

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值