How to capture and read headers of incoming HTTP requests in Flask? [duplicate]
You can use flask.request.headers
. It's a werkzeug.datastructures.EnvironHeaders
object, but you can use it as a normal dict.
For example:
from flask import Flask, requestapp = Flask(__name__)@app.route('/')def main(): print(request.headers) print(request.headers['User-Agent'])if __name__ == '__main__': app.run()
The output looks like:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Host: 127.0.0.1:5000Content-Type: Dnt: 1Content-Length: Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4Accept-Encoding: gzip, deflate, sdchCache-Control: max-age=0Connection: keep-aliveUpgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36