Python Forum

Full Version: Get HTTP Header ...
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I capture HTTP request headers and access their values, which native module do I use and how do I do it ?
The example is based only on the standard library of Python.

from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
# You can catch HTTPError and URLError


def get_header(url):
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:77.0) Gecko/20100101 Firefox/77.0"}
    request = Request(url, headers=header, method="HEAD")
    response = urlopen(request)
    if response.status == 200:
        return dict(response.headers)


get_header("https://python-forum.io/Thread-Get-HTTP-Header")
PS: User-Agent is often needed in Headers, because many web applications are checking if it's a real browser and not a bot.
The 3rd party requests module send some User-Agent string, which works in the most cases.
Thanks for the demonstration, I managed to do it as follows:

    # Function -> Main function that receives request web :
    def application(self, environ, start_response):

        # Function -> Get the type of content :
        v_cot = environ['CONTENT_TYPE']
Thanks.