Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 更改服务器头_Python_Flask_Werkzeug - Fatal编程技术网

Python 更改服务器头

Python 更改服务器头,python,flask,werkzeug,Python,Flask,Werkzeug,我制作了一个简单的烧瓶应用程序: 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:

我制作了一个简单的烧瓶应用程序:

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.
正在尝试127.0.0.1。。。
已连接到本地主机。
转义字符为“^]”。
GET/HTTP/1.1
主持人:google.be
未找到HTTP/1.0 404
内容类型:text/html
内容长度:233
服务器:Werkzeug/0.9.6 Python/2.7.6
日期:2014年12月8日星期一19:15:43 GMT
404找不到
找不到
在服务器上找不到请求的URL。如果您手动输入URL,请检查拼写并重试

连接被外部主机关闭。

我希望更改的内容之一是服务器头,目前它被设置为
Werkzeug/0.9.6 Python/2.7.6
,这是我自己选择的。但我在文档中似乎找不到任何关于如何执行此操作的信息。

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

from flask import make_response

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

您可以通过重写Flask.process\u response()方法更改每个响应的服务器头

从烧瓶导入烧瓶
从烧瓶导入响应
服务器名称='自定义Flask Web服务器v0.1.0'
局部烧瓶(烧瓶)等级:
def过程_响应(自我、响应):
#每个响应都将首先在此处处理
response.headers['server']=服务器名称
返回(响应)
app=localFlask(名称)
@应用程序路径(“/”)
def index():
返回('索引')
@应用程序路径(“/test”)
def test():
return('这是一个测试')

@bcarroll的答案有效,但它将绕过原始流程响应方法中定义的其他流程,如设置会话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)

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

这与您的要求没有太大关系,但在生产中,我会在web服务器层(即apache或nginx)执行此操作。如何使此标头跨所有路由全局?在调用超类的方法后设置服务器标头不是更好吗?例如,如果一个人不想设置它,但想删除它,只有在之后调用它才能工作。因此,在我看来,这似乎是一个更通用的解决方案
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)