zoukankan      html  css  js  c++  java
  • Flask接口返回JSON格式数据自动解析

    一 自定义一个response类

    from flask import Response, jsonify
    
    
    # 定义response返回类,自动解析json
    class JSONResponse(Response):
        @classmethod
        def force_type(cls, response, environ=None):
            if isinstance(response, dict):  # 判断返回类型是否是字典(JSON)
                response = jsonify(response)  # 转换
            return super().force_type(response, environ)

    二 主类注册app返回类

    app = Flask(__name__)
    app.debug = True  # 开启debug
    app.response_class = JSONResponse  # 指定返回类,解析json
    # 注册蓝图
    app.register_blueprint(other, url_prefix='/other')
    app.register_blueprint(user, url_prefix='/user')
    app.register_blueprint(order, url_prefix='/order')
    
    
    if __name__ == '__main__':
        app.run(port=8080)  # 端口默认5000

    三 测试

    视图函数,返回元组(json),其他数据不影响:

    @other.route('/json/')
    def json():
        return {"name": "Sam"}

  • 相关阅读:
    linux知识笔记4
    linux知识笔记3
    linux知识笔记2
    linux常用命令笔记1
    计算机网络
    软件测试理论5
    软件测试理论4
    软件测试理论3
    Yarn 常用命令
    mac shell终端编辑命令行快捷键
  • 原文地址:https://www.cnblogs.com/houzheng/p/10860080.html
Copyright © 2011-2022 走看看