Flask更改服务器标头

Luc*_*man 4 python werkzeug flask

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

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

我希望改变的一件事是服务器标题,此刻被设置为Werkzeug/0.9.6 Python/2.7.6我自己的选择.但我似乎无法在文档中找到有关如何执行此操作的任何内容.

Ish*_*aan 9

您可以使用Flask的make_response方法添加或修改标头.

from flask import make_response

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

  • 如何在所有路线上使此标题全局化? (2认同)

小智 6

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


bca*_*oll 5

您可以通过覆盖 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>')
Run Code Online (Sandbox Code Playgroud)

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