【问题标题】:Flask change the server headerFlask 更改服务器标头
【发布时间】:2014-12-08 19:22:06
【问题描述】:

我做了一个简单的烧瓶应用:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.1
host:google.be

HTTP/1.0 404 NOT FOUND
Content-Type: text/html
Content-Length: 233
Server: Werkzeug/0.9.6 Python/2.7.6
Date: Mon, 08 Dec 2014 19:15:43 GMT

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>
Connection closed by foreign host.

我想要更改的一件事是服务器标头,目前设置为Werkzeug/0.9.6 Python/2.7.6 以我自己选择的东西。但我似乎无法在文档中找到有关如何执行此操作的任何内容。

【问题讨论】:

  • 与您的要求并不密切,但在生产中,我会在 Web 服务器层(即 apache 或 nginx)执行此操作。

标签: python flask werkzeug


【解决方案1】:

您可以使用 Flask 的 ma​​ke_response 方法添加或修改标头。

from flask import make_response

@app.route('/index')
def index():
    resp = make_response("Hello, World!")
    resp.headers['server'] = 'ASD'
    return resp

【讨论】:

  • 我怎样才能使这个标头在所有路由中都是全局的?
【解决方案2】:

@bcarroll 的答案有效,但它会绕过原始 process_response 方法中定义的其他进程,例如设置会话 cookie。 为避免上述情况:

class localFlask(Flask):
    def process_response(self, response):
        #Every response will be processed here first
        response.headers['server'] = SERVER_NAME
        super(localFlask, self).process_response(response)
        return(response)

【讨论】:

  • 在调用超类'方法后设置服务器头不是更好吗?例如,如果不想设置它,但要删除它,那么只有在它之后调用它才会起作用。因此,在我看来,这是一个更通用的解决方案
【解决方案3】:

您可以通过覆盖 Flask.process_response() 方法来更改每个响应的服务器标头。

    from flask import Flask
    from flask import Response

    SERVER_NAME = 'Custom Flask Web Server v0.1.0'

    class localFlask(Flask):
        def process_response(self, response):
            #Every response will be processed here first
            response.headers['server'] = SERVER_NAME
            return(response)

    app = localFlask(__name__)


    @app.route('/')
    def index():
        return('<h2>INDEX</h2>')

    @app.route('/test')
    def test():
        return('<h2>This is a test</h2>')

http://flask.pocoo.org/docs/0.12/api/#flask.Flask.process_response

【讨论】:

  • 这对我有用...谢谢...
【解决方案4】:

如果您使用像 gunicorn 这样的生产服务器,则在代码中覆盖服务器标头不起作用。更好的方法是在 gunicorn 后面使用代理服务器并更改服务器标头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2014-04-30
    • 2021-03-16
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    相关资源
    最近更新 更多