一 自定义一个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"}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持免费资源网。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)