使用Flask接口如何实现如何自动解析JSON格式的数据

使用Flask接口如何实现如何自动解析JSON格式的数据

这篇文章将为大家详细讲解有关使用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"}

使用Flask接口如何实现如何自动解析JSON格式的数据

关于使用Flask接口如何实现如何自动解析JSON格式的数据就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。