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

时间:2014-09-16 03:42:47

标签: python flask

这是我的代码:

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

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

XMLHttpRequest cannot load http://localhost:5000/hello. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

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

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

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

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

修改

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

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>

有什么想法吗?

5 个答案:

答案 0 :(得分:66)

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

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

查看flask.Responseflask.make_response()

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

修改
我刚刚注意到你已经在使用make_response,这是其中一种方法。就像我之前说过的那样,after_request也应该起作用。尝试通过curl命中端点,看看标题是什么:

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标头。

编辑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

提供格式良好的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

答案 1 :(得分:12)

使用Flask之类的make_response

@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

来自flask docs

  

flask.make_response(* args)

     

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

答案 2 :(得分:7)

这是在我的flask应用程序中添加标头的方式,并且效果很好

first = {"MRF":40000,"RELIANCE":1000}
second = {"MRF":50000,"RELIANCE":2000}
third = {"MRF":30000,"RELIANCE":500}
fourth = {"MRF":60000,"RELIANCE":4000}

dicts = [first, second, third, fourth]
keys = first.keys()
new = {k: sum((d[k] for d in dicts)) / len(dicts) for k in first.keys()}
print(new) ## {'MRF': 45000.0, 'RELIANCE': 1875.0}

答案 3 :(得分:3)

这项工作对我来说

from flask import Flask
from flask import Response

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run()

答案 4 :(得分:0)

我们可以使用flask.g

使用Flask应用程序上下文在Python Flask应用程序中设置响应标头

这种使用flask.g在Flask应用程序上下文中设置响应标头的方法是线程安全的,可用于从任何应用程序文件设置定制和动态属性,如果我们要设置定制/动态响应,则这特别有用来自任何帮助程序类的标头,也可以从任何其他文件(例如中间件等)访问标头,此flask.g是全局的,并且仅对该请求线程有效。

如果我要从正在从此应用程序调用的另一个api / http调用中读取响应标头,然后提取任何内容并将其设置为该应用程序的响应标头。

示例代码:文件:helper.py

import flask
from flask import request, g
from multidict import CIMultiDict
from asyncio import TimeoutError as HttpTimeout
from aiohttp import ClientSession

    def _extract_response_header(response)
      """
      extracts response headers from response object 
      and stores that required response header in flask.g app context
      """
      headers = CIMultiDict(response.headers)
      if 'my_response_header' not in g:
        g.my_response_header= {}
        g.my_response_header['x-custom-header'] = headers['x-custom-header']


    async def call_post_api(post_body):
      """
      sample method to make post api call using aiohttp clientsession
      """
      try:
        async with ClientSession() as session:
          async with session.post(uri, headers=_headers, json=post_body) as response:
            responseResult = await response.read()
            _extract_headers(response, responseResult)
            response_text = await response.text()
      except (HttpTimeout, ConnectionError) as ex:
        raise HttpTimeout(exception_message)

文件:middleware.py

import flask
from flask import request, g

class SimpleMiddleWare(object):
    """
    Simple WSGI middleware
    """

    def __init__(self, app):
        self.app = app
        self._header_name = "any_request_header"

    def __call__(self, environ, start_response):
        """
        middleware to capture request header from incoming http request
        """
        request_id_header = environ.get(self._header_name)
        environ[self._header_name] = request_id_header

        def new_start_response(status, response_headers, exc_info=None):
            """
            set custom response headers
            """
            # set the request header as response header
            response_headers.append((self._header_name, request_id_header))
            # this is trying to access flask.g values set in helper class & set that as response header
            values = g.get(my_response_header, {})
            if values.get('x-custom-header'):
                response_headers.append(('x-custom-header', values.get('x-custom-header')))
            return start_response(status, response_headers, exc_info)

        return self.app(environ, new_start_response)

从主类中调用中间件

文件:main.py

from flask import Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare

    app = Flask(__name__)
    app.wsgi_app = SimpleMiddleWare(app.wsgi_app)