如何在 Flask 中设置响应头? [英] How do I set response headers in Flask?

查看:29
本文介绍了如何在 Flask 中设置响应头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

@app.route('/hello', methods=["POST"])
def hello():
    resp = make_response(render_template('hello.html'))
    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.

我也尝试过这种方法,将响应头设置为after"请求:

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.

编辑

如果我像这样使用 POST 请求来卷曲网址:

if I curl the url with a POST request like so:

curl -iX POST http://localhost:5000/hello

我收到了这个回复:

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>

有什么想法吗?

推荐答案

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

You can do this pretty easily:

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

查看 flask.Responseflask.make_response()

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

But something tells me you have another problem, because the after_request should have handled it correctly too.

编辑
我刚刚注意到您已经在使用 make_response 这是其中一种方法.就像我之前说的,after_request 应该也能工作.尝试通过 curl 访问端点并查看标头是什么:

EDIT
I just noticed you are already using make_response which is one of the ways to do it. Like I said before, after_request should have worked as well. Try hitting the endpoint via curl and see what the headers are:

curl -i http://127.0.0.1:5000/your/endpoint

你应该看到

> 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

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

Noting the Access-Control-Allow-Origin header.

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

EDIT 2
As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = True before you start the app and try again. You should get some output showing you the root cause of the problem.

例如:

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

提供一个格式良好的 html 错误页面,在底部(对 curl 命令有用)

Gives a nicely formatted html error page, with this at the bottom (helpful for curl command)

Traceback (most recent call last):
...
  File "/private/tmp/min.py", line 8, in home
    user.weapon = boomerang
NameError: global name 'boomerang' is not defined

这篇关于如何在 Flask 中设置响应头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆