Bootstrap FreeKB - Flask - GET HTTP Headers using the request module
Flask - GET HTTP Headers using the request module

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

In Flask, HTTP headers are made available using request. Let's say your flask project has the following structure.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

In your blueprint such as views.py, request can be used to capture the headers.

from flask import Blueprint, render_template, request

views = Blueprint('views', __name__)

@views.route('/')
def home():
    print("headers = " + str(request.headers))
    return render_template('base.html', headers=request.headers)

 

Which should return something like this.

Host: 127.0.0.1:5000
Connection: keep-alive
Cache-Control: max-age=0
Sec-Ch-Ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: http://127.0.0.1:5000/About
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

 

request.headers.get can be used to do something with a specific header.

from flask import Blueprint, render_template, request

views = Blueprint('views', __name__)

@views.route('/')
def home():
    useragent = request.headers.get("User-Agent")
    referer   = request.headers.get("Referer")
    print(f"useragent = {useragent}")
    print(f"referer   = {referer}")
    return render_template('base.html', useragent=useragent, referer=referer)

 

Or, instead of request.headers, you may want to use one of the other methods, such as request.url or request.path.

from flask import Blueprint, render_template, request

views = Blueprint('views', __name__)

@views.route('/')
def home():
    print(f"base url       = {request.base_url}")
    print(f"full path      = {request.full_path}")
    print(f"host           = {request.host}")
    print(f"host url       = {request.hosturl}")
    print(f"method         = {request.method}")
    print(f"path           = {request.path}")
    print(f"remote address = {request.remoteaddr}")
    print(f"scriptroot     = {request.scriptroot}")
    print(f"url            = {request.url}")
    print(f"url charset    = {request.urlcharset}")
    print(f"url root       = {request.urlroot}")
    print(f"url rule       = {request.urlrule}")
    print(f"HTTP_X_FORWARDED_FOR = {request.environ.get('HTTP_X_FORWARDED_FOR', request.remote_addr)}")
    return render_template('home.html')

 

Which should return something like this.

base url    = http://127.0.0.1:5000/Test
full path   = /Test?
host        = 127.0.0.1:5000
host url    = http://127.0.0.1:5000/
method      = GET
path        = /Test
script root =
url         = http://127.0.0.1:5000/Test
url charset = utf-8
url root    = http://127.0.0.1:5000/
url rule    = /Test
HTTP_X_FORWARDED_FOR = 198.11.55.185

 

Sometimes, you can use request in your HTML page, something like this.

<p>Request Path = {{ request.path }}</p>

 

Or, you can pass a value from your blueprint to your HTML page like using render_template. In this example, the first "referer" is the name of the variable that will be used in the HTML page and the second "referer" is the name of the variable in views.py.

from flask import Blueprint, render_template, request

views = Blueprint('views', __name__)

@views.route('/')
def home():
    referer = request.headers.get("Referer")
    return render_template('base.html', referer=referer)

 

And then you could use referer in base.html like this.

Referer = {{ referer }}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e2d6e0 in the box below so that we can be sure you are a human.