Flask视图函数默认是不能返回list对象和None的,如果返回数据不对,就会抛出异常
TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a JsonResponse.
以下将Flask改造为视图函数返回支持list、dict、None
json_flask.py
# -*- coding: utf-8 -*- from flask import Flask, jsonify from json_response import JsonResponse class JsonFlask(Flask): def make_response(self, rv): """视图函数可以直接返回: list、dict、None""" if rv is None or isinstance(rv, (list, dict)): rv = JsonResponse.success(rv) if isinstance(rv, JsonResponse): rv = jsonify(rv.to_dict()) return super().make_response(rv)
接口统一的返回格式 json_response.py
# -*- coding: utf-8 -*- class JsonResponse(object): """ 统一的json返回格式 """ def __init__(self, data, code, msg): self.data = data self.code = code self.msg = msg @classmethod def success(cls, data=None, code=0, msg='success'): return cls(data, code, msg) @classmethod def error(cls, data=None, code=-1, msg='error'): return cls(data, code, msg) def to_dict(self): return { "code": self.code, "msg": self.msg, "data": self.data }
使用改造后的JsonFlask对象
# -*- coding: utf-8 -*- from flask import Flask from flask_cors import CORS from json_flask import JsonFlask from json_response import JsonResponse # app = Flask(__name__) app = JsonFlask(__name__) CORS(app, supports_credentials=True) @app.route("/") def index(): return ['Tom', 'Jack'] @app.errorhandler(Exception) def error_handler(e): """ 全局异常捕获,也相当于一个视图函数 """ return JsonResponse.error(msg=str(e)) if __name__ == '__main__': app.run(port=5001)
访问接口返回的数据
{ "code": 0, "data": [ "Tom", "Jack" ], "msg": "success" }