Python 如何在 Flask 中设置响应头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25860304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set response headers in Flask?
提问by dopatraman
This is my code:
这是我的代码:
@app.route('/hello', methods=["POST"])
def hello():
resp = make_response()
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
However, when I make a request from the browser to my server I get this error:
但是,当我从浏览器向服务器发出请求时,出现此错误:
XMLHttpRequest cannot load http://localhost:5000/hello.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have also tried this approach, setting the response headers "after" the request:
我也尝试过这种方法,在请求“之后”设置响应头:
@app.after_request
def add_header(response):
response.headers['Access-Control-Allow-Origin'] = '*'
return response
No dice. I get the same error. Is there a way to just set the response headers in the route function? Something like this would be ideal:
没有骰子。我犯了同样的错误。有没有办法在路由函数中设置响应头?这样的事情将是理想的:
@app.route('/hello', methods=["POST"])
def hello(response): # is this a thing??
response.headers['Access-Control-Allow-Origin'] = '*'
return response
but I cant find anyway to do this. Please help.
但无论如何我都找不到这样做。请帮忙。
EDIT
编辑
if I curl the url with a POST request like so:
如果我使用 POST 请求卷曲 url,如下所示:
curl -iX POST http://localhost:5000/hello
I get this response:
我得到这个回应:
HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/html
Content-Length: 291
Server: Werkzeug/0.9.6 Python/2.7.6
Date: Tue, 16 Sep 2014 03:58:42 GMT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
Any ideas?
有任何想法吗?
回答by sberry
You can do this pretty easily:
你可以很容易地做到这一点:
@app.route("/")
def home():
resp = flask.Response("Foo bar baz")
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
Look at flask.Responseand flask.make_response()
看看flask.Response和flask.make_response()
But something tells me you have another problem, because the after_requestshould have handled it correctly too.
但是有些东西告诉我你还有另一个问题,因为after_request它也应该正确处理它。
EDIT
I just noticed you are already using make_responsewhich is one of the ways to do it. Like I said before, after_requestshould have worked as well. Try hitting the endpoint via curl and see what the headers are:
编辑
我刚刚注意到您已经在使用make_response这是其中一种方法。就像我之前说的,after_request应该也有效。尝试通过 curl 到达端点并查看标头是什么:
curl -i http://127.0.0.1:5000/your/endpoint
You should see
你应该看到
> curl -i 'http://127.0.0.1:5000/'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 11
Access-Control-Allow-Origin: *
Server: Werkzeug/0.8.3 Python/2.7.5
Date: Tue, 16 Sep 2014 03:47:13 GMT
Noting the Access-Control-Allow-Origin header.
注意 Access-Control-Allow-Origin 标头。
EDIT 2
As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = Truebefore you start the app and try again. You should get some output showing you the root cause of the problem.
编辑 2
正如我所怀疑的,你得到了 500,所以你没有像你想象的那样设置标题。app.debug = True在启动应用程序之前尝试添加并重试。您应该得到一些显示问题根本原因的输出。
For example:
例如:
@app.route("/")
def home():
resp = flask.Response("Foo bar baz")
user.weapon = boomerang
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
Gives a nicely formatted html error page, with this at the bottom (helpful for curl command)
给出一个格式很好的 html 错误页面,这个在底部(对 curl 命令很有帮助)
Traceback (most recent call last):
...
File "/private/tmp/min.py", line 8, in home
user.weapon = boomerang
NameError: global name 'boomerang' is not defined
回答by German Lopez
This work for me
这对我有用
from flask import Flask
from flask import Response
app = Flask(__name__)
@app.route("/")
def home():
return Response(headers={'Access-Control-Allow-Origin':'*'})
if __name__ == "__main__":
app.run()
回答by Devi
Use make_responseof Flask something like
使用make_responseFlask 之类的东西
@app.route("/")
def home():
resp = make_response("hello") #here you could use make_response(render_template(...)) too
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
From flask docs,
从烧瓶文档,
flask.make_response(*args)
Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
flask.make_response(*args)
有时需要在视图中设置额外的标题。因为视图不必返回响应对象,但可以返回一个值,该值由 Flask 本身转换为响应对象,因此向其添加标头变得棘手。可以调用此函数而不是使用返回值,您将获得一个可用于附加标头的响应对象。
回答by Cole.E
This was how added my headers in my flask application and it worked perfectly
这就是在我的 Flask 应用程序中添加我的头文件的方式,它工作得很好
@app.after_request
def add_header(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
return response

