5

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?

dvabhishek
  • 71
  • 1
  • 1
  • 4
  • 3
    How much of the [*Flask Quickstart*](http://flask.pocoo.org/docs/0.10/quickstart/#the-request-object) have you read? This is one of the *most basic* things you'd do in a web server environment. The [*API documentation*](http://flask.pocoo.org/docs/0.10/api/#incoming-request-data) also covers how to get request information. – Martijn Pieters Nov 21 '15 at 12:42
  • I have no idea about Flask, but I was able to get an answer in 2 minutes: [Request class](http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.Request) is what you're looking for. Is there any specific header outside of the easily accessible list that you're interested in? – Paweł Dyda Nov 21 '15 at 12:47

1 Answers1

11

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
Remi Guan
  • 21,506
  • 17
  • 64
  • 87