如何在Flask中设置响应标头?

dop*_*man 83 python flask

这是我的代码:

@app.route('/hello', methods=["POST"])
def hello():
    resp = make_response()
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
Run Code Online (Sandbox Code Playgroud)

但是,当我从浏览器向我的服务器发出请求时,我收到此错误:

XMLHttpRequest cannot load http://localhost:5000/hello. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

我也尝试过这种方法,在请求之后设置响应头:

@app.after_request
def add_header(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
Run Code Online (Sandbox Code Playgroud)

没有骰子.我犯了同样的错误.有没有办法在路由功能中设置响应头?这样的事情是理想的:

@app.route('/hello', methods=["POST"])
    def hello(response): # is this a thing??
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
Run Code Online (Sandbox Code Playgroud)

但无论如何我无法做到这一点.请帮忙.

编辑

如果我用这样的POST请求卷曲url:

curl -iX POST http://localhost:5000/hello
Run Code Online (Sandbox Code Playgroud)

我收到了这个回复:

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>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

sbe*_*rry 79

你可以很容易地做到这一点:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
Run Code Online (Sandbox Code Playgroud)

看看flask.Responseflask.make_response()

但有些东西告诉我你有另一个问题,因为它after_request应该也正确处理它.

编辑
我刚刚注意到你已经在使用make_response哪个是这样做的方法之一.就像我之前说过的,after_request应该也有效.尝试通过curl命中端点,看看标题是什么:

curl -i http://127.0.0.1:5000/your/endpoint
Run Code Online (Sandbox Code Playgroud)

你应该看到

> 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
Run Code Online (Sandbox Code Playgroud)

注意Access-Control-Allow-Origin标头.

编辑2
我怀疑,你得到500,所以你没有像你想象的那样设置标题.app.debug = True在启动应用程序之前尝试添加,然后重试.你应该得到一些输出显示问题的根本原因.

例如:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    user.weapon = boomerang
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
Run Code Online (Sandbox Code Playgroud)

给出一个格式良好的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
Run Code Online (Sandbox Code Playgroud)


小智 20

根据文档,您可以从视图函数中返回标头以及响应。

如果返回元组,则元组中的项目可以提供额外的信息。此类元组必须采用(response, status), (response, headers), 或 的形式(response, status, headers)。状态值将覆盖状态代码,标头可以是附加标头值的列表或字典。

例如:

@app.route('/hello', methods=["POST"])
def hello():
   return flask.make_response(), {"Access-Control-Allow-Origin": "*"}
Run Code Online (Sandbox Code Playgroud)

或者:

@app.route('/hello', methods=["POST"])
def hello():
   return {"foo": "bar"}, 200, {"Access-Control-Allow-Origin": "*"}
Run Code Online (Sandbox Code Playgroud)


Dev*_*evi 17

使用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
Run Code Online (Sandbox Code Playgroud)

来自flask文档,

flask.make_response(*参数)

有时需要在视图中设置其他标头.因为视图不必返回响应对象,但可以返回由Flask本身转换为响应对象的值,因此向其添加标题变得棘手.可以调用此函数而不是使用return,您将获得一个可用于附加标头的响应对象.


小智 12

这就是在我的 Flask 应用程序中添加我的头文件的方式,它工作得很好

@app.after_request
def add_header(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    return response
Run Code Online (Sandbox Code Playgroud)


Ger*_*pez 7

这对我有用

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()
Run Code Online (Sandbox Code Playgroud)

  • 还有一个符号 `return Response(headers={'Access-Control-Allow-Origin':'*'})` 对我来说看起来更干净。 (3认同)