In Flask, we can access HTTP headers using the request.headers
object.
To do this we write
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
# Get the headers from the request
headers = request.headers
# Print or process the headers
print("Headers:", headers)
# You can access specific headers using their keys
user_agent = headers.get('User-Agent')
print("User-Agent:", user_agent)
return "Check the console for headers."
if __name__ == '__main__':
app.run()
In this example, request.headers
contains all the headers sent in the HTTP request.
We can access specific headers using their keys, such as User-Agent
, Content-Type
, etc.
And we can also iterate over request.headers
to access all headers if needed.
When we run this Flask app and make a request to the /
route, it will print the headers in the console, and you can process them as needed.