如何在Flask中捕获和读取传入HTTP请求的标头?

时间:2015-11-21 12:37:45

标签: python http flask server analytics

我想读取传入请求的标头到我的服务器以跟踪其位置和其他属性。

例如: 如果有人点击了某个网址,我怎样才能读取传入请求的标题?

1 个答案:

答案 0 :(得分:4)

您可以使用flask.request.headers。它是werkzeug.datastructures.EnvironHeaders对象,但您可以将其用作普通字典。

例如:

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def main():
    print(request.headers)
    print(request.headers['User-Agent'])

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

输出如下:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Host: 127.0.0.1:5000
Content-Type: 
Dnt: 1
Content-Length: 
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Encoding: gzip, deflate, sdch
Cache-Control: max-age=0
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36


Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36