如何通过不允许的方法(如PUT,DELETE ...)请求应用程序时返回json输出?

kin*_*chi 2 python api flask

我正在使用Flask实现API.
问题是,当通过不允许的方法请求api时,API返回错误的html页面.我想为此返回json值.我怎么能在Flask中做到这一点?

提前致谢.

Sea*_*ira 5

只需使用errorhandler装饰器或register_error_handler方法返回适当的JSON:

@app.errorhandler(404)
def error_404():
    return jsonify(error="This resource does not exist"), 404
Run Code Online (Sandbox Code Playgroud)