简体   繁体   English

Flask-Restful中的忽略方法,忽略CORS选项

[英]abort method in Flask-Restful ignoring CORS options

I have a Flask-Restful API configured with some CORS options: 我有一个Flask-Restful API,配置了一些CORS选项:

api = Api()
api.decorators=[cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])]

...

api.init_app(app)

My API accepts POST requests which may fail if the data in the request is invalid: 我的API接受POST请求,如果请求中的数据无效,则该请求可能会失败:

class myAPI(Resource):
    def post(self):
        args = request.get_json()
        if args.get('something'):
            return {'message': 'Request worked, data received!',
                    'something': args['something']}
        else:
            abort(500, "Error: Data must contain a 'something' field!")

When I make a successful POST request to my API I can see that the CORS options are properly set: 当我向我的API发出成功的POST请求时,我可以看到正确设置了CORS选项:

...
* upload completely sent off: 81 out of 81 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 205
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: HEAD, GET, POST, OPTIONS
< Access-Control-Max-Age: 21600
< Access-Control-Allow-Headers: ACCEPT, CONTENT-TYPE
< Server: Werkzeug/0.9.4 Python/2.7.6

If, however, the post call in my class exits through the abort method (by purposely sending bad data to the request) then the Access-Control-* fields are all missing from the response: 但是,如果我类中的post调用通过abort方法退出(有意向请求发送错误的数据),则响应中的Access-Control-*字段都将丢失:

* upload completely sent off: 75 out of 75 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 500 INTERNAL SERVER ERROR
< Content-Type: application/json
< Content-Length: 51
< Server: Werkzeug/0.9.4 Python/2.7.6

Is it possible to make the abort method play nice with my CORS rules, or should I create my own full-fledged response and avoid using the abort function? 是否可以使abort方法与我的CORS规则配合使用,还是应该创建自己的完整响应并避免使用abort函数?

When you trigger an abort, the error handler registered to the HTTP error code is automatically invoked, and the response is not actually served by your view function. 当您触发异常终止时,注册到HTTP错误代码的错误处理程序将自动被调用,并且视图函数实际上不会响应该响应。

If you use the CORS middleware which is provided by Flask-Cors, instead of the decorator form, in the case of handled exceptions and aborts, the CORS headers will be injected as expected. 如果使用Flask-Cors提供的CORS中间件而不是装饰器形式,则在处理异常和异常终止的情况下,将按预期注入CORS标头。

If an unhandled exception occurs, (EG there is an error in your code, and a 500 internal server error), Flask bypasses middleware, and after_request handlers are not run. 如果发生未处理的异常(例如,您的代码中存在错误,并且内部服务器错误为500),则Flask会绕过中间件,并且after_request处理程序不会运行。

Full disclosure, I wrote Flask-Cors. 完全披露,我写了Flask-Cors。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM