ndg-httpsclient: Enhanced HTTPS with PyOpenSSL

0.5.1 · active · verified Thu Apr 09

ndg-httpsclient provides enhanced HTTPS support for Python's standard library modules `httplib` and `urllib2` (Python 2) or `http.client` and `urllib.request` (Python 3) using PyOpenSSL. It allows for advanced SSL/TLS features like Server Name Indication (SNI) and robust peer certificate verification, extending capabilities beyond the default standard library implementation. The current version is 0.5.1, with a relatively slow release cadence focused on compatibility and critical fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using `ndg-httpsclient`'s `open_url` utility to make an HTTPS request. This function internally leverages the PyOpenSSL-enhanced `HTTPSHandler` that the library integrates into Python's standard HTTP client modules. For more advanced use, like client certificate authentication or custom CA bundles, additional arguments can be passed to `open_url`.

import sys
import ssl
# PyOpenSSL is a dependency that ndg-httpsclient leverages
from OpenSSL import SSL

# ndg-httpsclient patches these modules, so they should benefit from its enhancements
if sys.version_info[0] >= 3:
    import urllib.request as request_mod
    import http.client as http_client_mod
else:
    import urllib2 as request_mod
    import httplib as http_client_mod

# The primary utility for direct use is open_url
from ndg.httpsclient.utils import open_url

# For this example, we'll try a common HTTPS URL.
# In a real-world scenario, you might pass specific client certificates (c, k)
# or a custom CA bundle (ca) for peer verification.
target_url = "https://www.google.com"

print(f"Attempting to connect to {target_url} using ndg-httpsclient's open_url...")

try:
    # open_url utilizes the PyOpenSSL-backed HTTPS handling provided by ndg-httpsclient
    # For more robust verification, you'd provide `ca='path/to/ca-bundle.pem'`
    response = open_url(target_url)

    print(f"Connection successful!")
    print(f"HTTP Status Code: {response.getcode()}")
    print(f"Content-Type: {response.info()['Content-Type']}")
    # Read and decode a small part of the content to demonstrate success
    # Do not read full content for quickstart to avoid large output
    content_snippet = response.read(200).decode('utf-8', errors='ignore')
    print(f"Partial Content: {content_snippet}...")

except SSL.Error as e:
    print(f"SSL Error during connection: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →