flask路由分模块管理及自定义restful响应格式详解

来自:网络
时间:2022-12-28
阅读:
目录

一、flask路由分模块管理

1.1、使用蓝图

在flask中可以使用蓝图Blueprint来进行创建路由进行分模块。 具体操作,我们可以在项目根目录下创建一个controller文件夹来存储分模块的路由。

在controller文件夹里创建product_controller.py,在里面如下写法引入蓝图,并且注册蓝图:

from flask import Blueprint
product_blue = Blueprint('product', __name__)
# 定义蓝图路径及请求方法和请求返回逻辑
@product_blue.route('/get', methods=['get', 'post'])
def getproduct():
	return 'product'
@product_blue.route('/search', methods=['get', 'post'])
def searchproduct():
	return 'search'

那么我们在项目主逻辑文件main.py中,去引入并注册这个蓝图:

from flask import Flask
from controller.product_controller import product_blue
app = Flask(__name__)
# 商品模块
app.register_blueprint(product_blue, url_prefix='/product')
if __name__ == '__main__':
    app.run()

接下来我们运行程序,可以看到如下效果:

flask路由分模块管理及自定义restful响应格式详解

flask路由分模块管理及自定义restful响应格式详解

可以看到我们使用蓝图分模块的创建已经生效了,这样如果模块对的话,我们就方便管理了。不会造成代码全部冗余在一个主文件中。

1.2、使用flask_restful

那么相比与蓝图Blueprint,flask_restful的优势就在于它能够做更多的操作,比如参数的验证,返回直接字典就能解析成json

首先我们输入命令pip3 install flask_restful安装flask_restful。 在product_controller中写入如下代码:

from flask_restful import Resource, reqparse
class ProductView(Resource):
    @staticmethod
    def post():
        parse = reqparse.RequestParser()
        parse.add_argument('product_id', type=str, help='商品id必传', required=True, trim=True)
        args = parse.parse_args()
        product_id = args.product_id
        return {
            'msg': '商品id是' + product_id,
            'code': 200
        }
    @staticmethod
    def get():
        return {
            'msg': '商品',
            'code': 200
        }

那么main.py主文件中修改如下:

from controller.product_controller import ProductView
app = Flask(__name__)
api = Api(app)
api.add_resource(ProductView, '/product', endpoint='product')
if __name__ == '__main__':
    app.run()

现在已经是restful形式的api了,我们采用apifox或者postman测试请求接口如下:

flask路由分模块管理及自定义restful响应格式详解

flask路由分模块管理及自定义restful响应格式详解

flask路由分模块管理及自定义restful响应格式详解

可以看到get请求成功,但是在post请求时,我们没有传必传参数,所以出现了报错。我们尝试将必传参数加上:

flask路由分模块管理及自定义restful响应格式详解

flask路由分模块管理及自定义restful响应格式详解

那么可以看到将必传的参数加上后,请求成功。 两种模式可以共存,但是一般我们只用一种就行了。

相信细心的小伙伴已经发现,失败和成功返回的数据格式不一样,成功有code,失败却没有code,那么我想自定义失败返回的数据格式,将怎么操作呢,接下来自定义flask_restful的错误响应。

二、自定义flask_restful响应格式

在根目录下创建errors.py,写入如下代码:

"""
design the custom error response of flask-restful
"""
from flask_restful import abort
def generate_response(msg, status):
    return {
            'code': status,
            'msg': msg,
        }
def custom_abort(http_status_code, *args, **kwargs):
    if http_status_code == 400:
        abort(400, **generate_response(msg=[kwargs.get('message')], status=http_status_code))
    abort(http_status_code)

我们将错误状态拎出来自定义返回格式。 在main.py主文件中加入这两行代码:

from errors import custom_abort
flask_restful.abort = custom_abort

效果如下:

flask路由分模块管理及自定义restful响应格式详解

可以看到我们成功的返回了相同的数据结构。

以上就是flask路由分模块管理及自定义restful响应格式详解的详细内容,更多关于flask路由管理restful响应格式的资料请关注其它相关文章!

返回顶部
顶部