在flask中自定义响应数据的格式。
目录结构:
├── demoflask.py
├── main
│ ├── __init__.py
│ ├── errors.py
errors.py
中分别定义处理响应和异常的函数generate_response
、my_abort
# coding:utf-8
from flask_restful import abort
class ResponseCode:
SUCCESS = 200
WRONG_PARAM = 400
MESSAGE = '处理成功!'
def generate_response(data=None, message=ResponseCode.MESSAGE, status=ResponseCode.SUCCESS):
return {
'message': message,
'status': status,
'data': data
}
def my_abort(http_status_code, *args, **kwargs):
if http_status_code == 400:
# 重定义400返回参数
abort(400, **generate_response(data=[kwargs.get('message')], message='参数错误!', status=http_status_code))
abort(http_status_code)
再在demoflask.py
中注册restful的异常处理
import flask_restful
import os
from flask_restful import request
from werkzeug.datastructures import FileStorage
from flask import Flask
from flask_restful import Resource, Api, reqparse
from main.errors import my_abort, generate_response
app = Flask(__name__)
api = Api(app=app)
ddir = os.getcwd()
# 自定义错误
flask_restful.abort = my_abort
class UserInfos(Resource):
def __init__(self):
self.parser = reqparse.RequestParser(bundle_errors=True)
self.parser.add_argument('name', type=str, required=True, help='缺少该参数')
self.parser.add_argument('email', type=str, required=True, help='缺少该参数')
self.parser.add_argument('address', type=str, required=True, help='缺少该参数')
def post(self):
self.parser.parse_args()
print('OK')
return generate_response()
#
# DataApi
#
class DataApi(Resource):
"""
数据接口
"""
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('file', required=True, type=FileStorage, help='csv file', location='files')
def post(self):
file = request.files['file']
print(file.name, file.mimetype, file.stream)
file.save('test.png')
return generate_response()
api.add_resource(DataApi, '/data')
api.add_resource(UserInfos, '/user')
if __name__ == '__main__':
app.run(debug=True)
正常数据:
在调用/user
接口时,如果是400
错误,则会按照我们自定义的方式返回响应数据。