Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture and read headers of incoming HTTP requests in Flask? [duplicate]

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?

like image 800
dvabhishek Avatar asked Nov 21 '15 12:11

dvabhishek


1 Answers

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
like image 163
Remi Crystal Avatar answered Nov 15 '22 09:11

Remi Crystal