All Course > Python > Build Apis With Python Urllib3 Dec 06, 2023

Disabling hostname verification in Python example

Sometimes you may need to disable hostname verification in your Python programs based on the organization's requirements. Hostname verification is a part of HTTPS connection. That verifies client is talking to the correct server to avoid man-of-the-middle attacks.

The bellow code shows how to disable hostname verification in Python’s urllib3 library. To do that we will use  HTTPSConnectionPool class. Along with disabling hostname verification, I will implement retry also.

Read more on SSL and how it works here.

Check out *this article for more details about Python Retry implementation

Disabling hostname verification in Python GET and POST

We will use publicly available API from gorest.co.in to demonstrate the disabling hostname verification. Also, we will use the parse_url module from urlib3.util

# get - disabling hostname verification
from urllib3.util import parse_url
from urllib3.util.retry import Retry
import json


def get():
    try:
        url = "https://gorest.co.in/public/v2/users"
        url_output = parse_url(url)
        path = url_output.path

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
        }

        retries = Retry(
            total=3,
            read=3,
            connect=3,
            backoff_factor=2,
        )

        pool = urllib3.HTTPSConnectionPool(
            url_output.hostname,
            port=443,
            cert_reqs="CERT_REQUIRED",
            assert_hostname=False,
            timeout=30,
            retries=retries,
            ca_certs="path-to-cert",
        )

        res = pool.request(
            "GET",
            path,
            headers=headers,
        )

        if res.status != 200:
            if res.data:
                print(f"Error message: {res.data}")

            raise Exception(f"Request is failed, status: {res.status}")
        print(json.loads(res.data.decode("utf-8")))

    except Exception as e:
        raise Exception(f"Error while request: {e}")


if __name__ == "__main__":
    get()
# post - disabling hostname verification
import json
import urllib3
from urllib3.util import parse_url
from urllib3.util.retry import Retry


def post():
    try:
        url = "https://gorest.co.in/public/v2/users"
        url_output = parse_url(url)
        path = url_output.path

        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
        }

        payload = {
            "name": "Tenali Ramakrishna",
            "gender": "male",
            "email": "[email protected]",
            "status": "active",
        }

        retries = Retry(
            total=3,
            read=3,
            connect=3,
            backoff_factor=2,
        )

        pool = urllib3.HTTPSConnectionPool(
            url_output.hostname,
            port=443,
            cert_reqs="CERT_REQUIRED",
            assert_hostname=False,
            timeout=30,
            retries=retries,
            ca_certs="path-to-cert",
        )

        res = pool.urlopen(
            "POST", path, headers=headers, body=json.dumps(payload)
        )

        if res.status != 201:
            if res.data:
                print(f"Error message: {res.data}")
            raise Exception(f"Request is failed, status: {res.status}")
        return json.loads(res.data.decode("utf-8"))

    except Exception as e:
        raise Exception(f"Error while request: {e}")


if __name__ == "__main__":
    post()

Conclusion

To disable hostname verification in Python we can use urllib3 library. The HTTPSConnectionPool class accepts the assert_hostname argument.

Comments

There are no comments yet.

Write a comment

You can use the Markdown syntax to format your comment.

Tags: disable hostname urllib3