我只是酒瓶里的新手。试着把棉花糖和香肠结合起来。它完美地工作在烧瓶-restful资源类中。但是当我使用一个简单的烧瓶路线时,它就不起作用了。
routes.py
class UserAPI(Resource):
@use_args(UserSchema())
def post(self, *args):
print(args)
return 'success', 201
def get(self):
return '<h1>Hello</h1>'
@bp.route('/test/', methods=['POST'])
@use_kwargs(UserSchema())
def test2(*args, **kwargs):
print(args)
print(kwargs)
return 'success', 201
api.add_resource(UserAPI, '/', endpoint='user')
我添加了错误处理程序,这在使用use_args时是必要的
from webargs.flaskparser import parser, abort
from webargs import core
@parser.error_handler
def webargs_validation_handler(error, req, schema, *, error_status_code, error_headers):
status_code = error_status_code or core.DEFAULT_VALIDATION_STATUS
abort(
400,
exc=error,
messages=error.messages,
)
当我向Resource端点发出请求时,这就是我所得到的,这是正常的
当我要求一个简单的烧瓶路线时,这就是不正常的
我希望能同时使用两种方式
发布于 2022-04-13 05:40:30
在webargs docs :) https://webargs.readthedocs.io/en/latest/framework_support.html#error-handling中找到答案
from flask import jsonify
# Return validation errors as JSON
@app.errorhandler(422)
@app.errorhandler(400)
def handle_error(err):
headers = err.data.get("headers", None)
messages = err.data.get("messages", ["Invalid request."])
if headers:
return jsonify({"errors": messages}), err.code, headers
else:
return jsonify({"errors": messages}), err.code
https://stackoverflow.com/questions/71710815
复制相似问题