I want to read the headers of an incoming request to my server to track its location and other attributes.
For example: If someone clicks on an URL, how will I be able to read the headers of the incoming request?
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, request
app = 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.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With