### Example Usage of contents() Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/core-module.md Demonstrates how to get the CA bundle contents as a string and use it with the SSL module. Includes checks for specific issuers and PEM format. ```python from certifi.core import contents # Get certificate bundle as string certs = contents() # Check for specific issuer if "CN=ISRG Root X1" in certs: print("ISRG Root X1 is present in the bundle") # Use with SSL module import ssl context = ssl.create_default_context() context.load_verify_locations(cadata=contents()) # Verify PEM format assert certs.count("-----BEGIN CERTIFICATE-----") > 0 assert certs.count("-----END CERTIFICATE-----") > 0 ``` -------------------------------- ### Install Certifi from Source Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/package-structure.md Instructions for cloning the certifi repository from GitHub and installing it locally using pip. ```bash git clone https://github.com/certifi/python-certifi.git cd python-certifi pip install . ``` -------------------------------- ### Example Usage of where() Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/core-module.md Demonstrates how to get the CA bundle path and use it with an SSL context. Verifies the file's existence. ```python from certifi.core import where # Get the path to the CA bundle path = where() print(path) # Verify file exists import os assert os.path.exists(path) # Use with SSL context import ssl context = ssl.create_default_context(cafile=path) ``` -------------------------------- ### Get Certifi Installation Path Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/package-structure.md Demonstrates how to obtain the installation path of the `cacert.pem` file using the `certifi.where()` function and direct file system access. ```python import os certifi_dir = os.path.dirname(certifi.__file__) cacert_path = os.path.join(certifi_dir, 'cacert.pem') ``` -------------------------------- ### Docker Usage: Install and Use Certifi Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Demonstrates how to install certifi in a Docker image and set the REQUESTS_CA_BUNDLE environment variable to use the certificates. ```dockerfile FROM python:3.11-slim RUN pip install certifi # Use certifi path in environment ENV REQUESTS_CA_BUNDLE=/cacert.pem RUN python -m certifi > /cacert.pem # Or inline in Dockerfile RUN python -c "import certifi; print(open(certifi.where()).read())" > /cacert.pem ``` -------------------------------- ### Using Certifi with Type Hints Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/types.md A basic example of importing the certifi library and using it with a type hint for a constant. ```python import certifi from typing import Final ``` -------------------------------- ### Complete Example Certificate Entry Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/certificate-bundle-format.md An example of a complete certificate entry in PEM format, including metadata headers and the Base64-encoded certificate data. ```text # Issuer: CN=ISRG Root X1 O=Internet Security Research Group C=US # Subject: CN=ISRG Root X1 O=Internet Security Research Group C=US # Label: "ISRG Root X1" # Serial: 173666528029954357065925684967207960652 # MD5 Fingerprint: 0c:d2:f9:e0:da:47:2c:4e:fa:b9:d6:59:a9:c4:3d:0a # SHA1 Fingerprint: ca:bd:2a:79:a1:ab:6c:4d:ca:fb:e8:ab:05:95:0f:2f:e0:a3:05:e0 # SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:cc:b4:13:e3:7a:55:16:f5:57:f7:fd:0b:b6:4b:40:d6:48:6d:3f:cf:04:92 -----BEGIN CERTIFICATE----- MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2FrpDAwDQYJKoZIhvcNAQELBQAw RzELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGElu dGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0xNjA2MDYwMjA0NTZaFw00MzEwMjEw MjA0NTZaMEcxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYD VQQDDBZJQ1AgU2VydmVyIENlcnRpZmljYXRlMIICIjANBgkqhkiG9w0BAQEFAAOC AgoPAIICCgKCAgEAu3HM4X3lNfEHN8rYJEb2K5MVWT8qVRvk7m3J9YJKyqIrPNAK ... JzKHbqA+3OsQP7vcm9sWFqKVlIRpLqXGnlP4aNHGQs5n/jIKPLWi+j8Q6rCmHWOJ -----END CERTIFICATE----- ``` -------------------------------- ### Verify Certifi Installation and Bundle Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md Check the installed certifi version, the path to the certificate bundle, and verify its existence, readability, and the number of certificates it contains. ```python import certifi import os print(f"certifi version: {certifi.__version__}") print(f"Certificate bundle path: {certifi.where()}") # Verify file exists path = certifi.where() if os.path.exists(path): size = os.path.getsize(path) print(f"✓ File exists ({size} bytes)") else: print("✗ File does not exist") # Verify readable if os.access(path, os.R_OK): print("✓ File is readable") else: print("✗ File is not readable") # Check contents try: contents = certifi.contents() cert_count = contents.count("-----BEGIN CERTIFICATE-----") print(f"✓ Contains {cert_count} certificates") except Exception as e: print(f"✗ Error reading contents: {e}") ``` -------------------------------- ### Workaround: Verify Installation and Read Permissions Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Checks if the certificate bundle exists and is readable, addressing potential path issues in some virtual environment configurations. ```python import os import certifi assert os.path.exists(certifi.where()) assert os.access(certifi.where(), os.R_OK) ``` -------------------------------- ### Pinning Specific Certificates (Partial Example) Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md This snippet is part of an example demonstrating how to pin specific certificates. It shows how to retrieve certificate data using Certifi, which is a prerequisite for further processing with libraries like cryptography. ```python import ssl import certifi from cryptography import x509 from cryptography.hazmat.backends import default_backend import re # Get certificate data cert_data = certifi.contents() ``` -------------------------------- ### Verify Certifi Installation Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Verify that certifi is installed correctly by checking if its CA bundle path exists and contains valid certificate data. ```python import certifi import os # Check path exists assert os.path.exists(certifi.where()) # Check contents assert len(certifi.contents()) > 0 assert "-----BEGIN CERTIFICATE-----" in certifi.contents() print("✓ Certifi is properly installed") ``` -------------------------------- ### Windows Path Output Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Example of the default path output on a Windows system. ```cmd C:\> python -m certifi C:\Users\username\AppData\Local\Programs\Python\Python311\lib\site-packages\certifi\cacert.pem ``` -------------------------------- ### macOS Path Output Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Example of the default path output on a macOS system. ```bash $ python -m certifi /Library/Python/3.11/site-packages/certifi/cacert.pem ``` -------------------------------- ### Install Certifi using pip Source: https://github.com/certifi/python-certifi/blob/master/README.rst Install the certifi package using pip. This is the standard method for adding certifi to your Python environment. ```bash $ pip install certifi ``` -------------------------------- ### Get Certifi CA Bundle Path (Command Line) Source: https://github.com/certifi/python-certifi/blob/master/README.rst Execute the certifi module from the command line to print the absolute path to the installed CA bundle. This is useful for quick checks or scripting. ```bash $ python -m certifi ``` -------------------------------- ### Combine Custom Certificates with Certifi Bundle Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/README.md Example showing how to create a combined certificate bundle by concatenating certifi.contents() with a custom PEM file. ```python import certifi combined = certifi.contents() + "\n" + open('custom.pem').read() ``` -------------------------------- ### Kubernetes ConfigMap and Pod Setup Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Illustrates how to create a Kubernetes ConfigMap containing the CA bundle and mount it into a Pod, setting the REQUESTS_CA_BUNDLE environment variable. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: ca-bundle data: cacert.pem: | -----BEGIN CERTIFICATE----- # ... certificate data ... -----END CERTIFICATE----- --- apiVersion: v1 kind: Pod metadata: name: my-app spec: containers: - name: app image: python:3.11 volumeMounts: - name: ca-certs mountPath: /etc/ssl/certs env: - name: REQUESTS_CA_BUNDLE value: /etc/ssl/certs/cacert.pem volumes: - name: ca-certs configMap: name: ca-bundle ``` -------------------------------- ### Get Certifi Version Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Retrieve the installed version of the certifi package. ```python import certifi print(certifi.__version__) # Output: "2026.05.20" (date-based version) ``` -------------------------------- ### Certifi CLI Exit Code Example Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Demonstrates a successful execution of the certifi CLI, showing the output path and the exit code 0. ```bash $ python -m certifi; echo "Exit code: $?" /usr/local/lib/python3.11/site-packages/certifi/cacert.pem Exit code: 0 ``` -------------------------------- ### Verify Certifi Installation Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/README.md Python code to verify that certifi is installed correctly by checking the existence of the path returned by certifi.where() and the content length returned by certifi.contents(). ```python import certifi import os assert os.path.exists(certifi.where()) assert len(certifi.contents()) > 0 ``` -------------------------------- ### Verifying Certifi Installation Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md A Python function to verify that the certifi bundle is correctly installed by checking its existence, readability, and content. ```python import certifi import os def verify_installation(): """Verify certifi is correctly installed.""" path = certifi.where() # Check existence assert os.path.exists(path), "Bundle file not found" # Check readability assert os.access(path, os.R_OK), "Bundle is not readable" # Check content is valid contents = certifi.contents() assert len(contents) > 0, "Bundle is empty" assert contents.count("-----BEGIN CERTIFICATE-----") > 50, "Bundle has too few certificates" return True assert verify_installation(), "Certifi installation verification failed" ``` -------------------------------- ### Using HTTPS with Requests and Certifi Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md Example demonstrating the secure practice of always using the verify parameter with certifi.where() when making HTTPS requests with the requests library. ```python import requests import certifi # Always use verify parameter response = requests.get( 'https://api.example.com', verify=certifi.where() ) # Never do this: # response = requests.get('https://api.example.com', verify=False) # INSECURE! ``` -------------------------------- ### Dockerfile: Integrating Certifi CA Bundle Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Example Dockerfile instruction to output the certifi CA bundle to a standard location and set the `REQUESTS_CA_BUNDLE` environment variable. ```dockerfile # Use certifi to provide CA bundle RUN python -m certifi > /etc/ssl/certs/ca-bundle.crt ENV REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-bundle.crt ``` -------------------------------- ### Troubleshooting: File Not Found Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Error message indicating that the `cacert.pem` resource cannot be found. This suggests an incomplete or corrupted certifi installation, which can be fixed by reinstalling the package. ```bash Traceback (most recent call last): ... FileNotFoundError: Cannot find resource 'cacert.pem' ``` -------------------------------- ### Troubleshooting: Module Not Found Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Error message indicating that the `certifi` module cannot be found. The solution is to install it using pip. ```bash $ python -m certifi No module named certifi ``` -------------------------------- ### Import and Use Certifi Functions Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/README.md Import the `where` and `contents` functions from the certifi module to get the CA bundle path or its content as a string. ```python from certifi import where, contents path = where() # Returns: "/path/to/certifi/cacert.pem" certs = contents() # Returns: PEM-formatted certificate data ``` -------------------------------- ### Certifi Function Signatures (No Parameters) Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/types.md Demonstrates the correct function signatures for `where()` and `contents()`, which accept no parameters and return a string. Shows examples of correct and invalid calls. ```python def where() -> str: # Returns absolute filesystem path ... def contents() -> str: # Returns certificate bundle as string ... # Correct path = where() content = contents() # Invalid - TypeError path = where("some/path") # TypeError content = contents("utf-8") # TypeError ``` -------------------------------- ### Handle Certificate Bundle Not Found Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/types.md Example of how to handle potential FileNotFoundError when accessing the certificate bundle using certifi.where(). ```python import certifi try: path = certifi.where() except FileNotFoundError: print("Certificate bundle not found") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Use certifi.where() with Requests for SSL Verification Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/README.md Example demonstrating the correct usage of certifi.where() with the 'verify' parameter in the requests.get() function for SSL certificate verification. ```python import requests import certifi response = requests.get(url, verify=certifi.where()) # Note: verify parameter ``` -------------------------------- ### Bash Script: Get CA Bundle Contents and Use Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Shows how to save the CA bundle contents to a temporary file and use it with tools like curl. Includes cleanup of the temporary file. ```bash #!/bin/bash # Save bundle to a temporary file TEMP_BUNDLE=$(mktemp) python -m certifi --contents > "$TEMP_BUNDLE" # Use with curl curl --cacert "$TEMP_BUNDLE" https://api.example.com # Cleanup rm "$TEMP_BUNDLE" ``` -------------------------------- ### Get CA Bundle Contents via Command Line Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Retrieve the CA bundle contents using the certifi module with the --contents flag. ```bash $ python -m certifi --contents # Issuer: CN=Example Root CA -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- ``` -------------------------------- ### Example Certificate Entry Format Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/certifi-module.md Illustrates the standard PEM format for a CA certificate entry, including issuer, subject, label, serial number, and fingerprints, followed by the Base64-encoded certificate data. ```text # Issuer: CN=Example Root CA O=Example Inc. # Subject: CN=Example Root CA O=Example Inc. # Label: "Example Root CA" # Serial: 123456789 # MD5 Fingerprint: xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx # SHA1 Fingerprint: xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx # SHA256 Fingerprint: xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx -----BEGIN CERTIFICATE----- [Base64-encoded certificate data] -----END CERTIFICATE----- ``` -------------------------------- ### Type Checking Example Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/package-structure.md Illustrates how to use `TYPE_CHECKING` to import types for static analysis without affecting runtime behavior. The type checker will recognize the return types of `where` and `contents`. ```python from typing import TYPE_CHECKING if TYPE_CHECKING: from certifi import where, contents # Type checker knows: # where() -> str # contents() -> str ``` -------------------------------- ### Get CA Bundle Contents (Python 3.11+) Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/core-module.md Reads and returns the entire content of the cacert.pem file as a string using modern importlib.resources. The file is read with ASCII encoding. ```python from importlib.resources import files return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii") ``` -------------------------------- ### Get CA Bundle Contents (Python 3.7-3.10) Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/core-module.md Reads and returns the entire content of the cacert.pem file as a string using legacy importlib.resources. The file is read with ASCII encoding. ```python from importlib.resources import read_text return read_text("certifi", "cacert.pem", encoding="ascii") ``` -------------------------------- ### Get CA Bundle Path (Python 3.7-3.10) Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/core-module.md Retrieves the filesystem path to the bundled cacert.pem file using legacy importlib.resources. This path is cached after the first access. ```python from importlib.resources import path as get_path _CACERT_CTX = get_path("certifi", "cacert.pem") _CACERT_PATH = str(_CACERT_CTX.__enter__()) ``` -------------------------------- ### Use Certifi Path in Shell Scripts Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Examples of using the certifi CA bundle path in shell scripts with tools like curl, wget, and git. ```bash #!/bin/bash # Export as environment variable export REQUESTS_CA_BUNDLE=$(python -m certifi) # Use with curl curl --cacert $(python -m certifi) https://api.example.com # Use with wget wget --ca-certificate=$(python -m certifi) https://api.example.com/file # Use with git git config --global http.sslCAInfo "$(python -m certifi)" ``` -------------------------------- ### Certifi where() function behavior across Python versions Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md This example demonstrates the functional equivalence of the certifi.where() function across different Python versions, showing that both legacy and modern implementations return the same path to the cacert.pem file. ```python # Python 3.7-3.10 behavior ca_path = certifi.where() # Result: "/path/to/certifi/cacert.pem" # Python 3.11+ behavior (same result) ca_path = certifi.where() # Result: "/path/to/certifi/cacert.pem" # Both guarantee: # - String return type # - File exists and is readable # - Path is cached within process # - Identical contents ``` -------------------------------- ### Get Certifi CA Bundle Path (Python) Source: https://github.com/certifi/python-certifi/blob/master/README.rst Import the certifi module and use the where() function to get the absolute path to the installed CA bundle. This path can be used by other libraries to verify SSL certificates. ```python import certifi certifi.where() ``` -------------------------------- ### Minimal pyproject.toml Configuration Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/package-structure.md A basic `pyproject.toml` file specifying the build system requirements and backend for the setuptools build process. ```toml [build-system] requires = ["setuptools >= 42.0.0"] build-backend = "setuptools.build_meta" ``` -------------------------------- ### Create SSL Context with Certifi Bundle Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/types.md Demonstrates how to create an SSL context, optionally using certifi's CA bundle if no custom CA path is provided. ```python from typing import Optional import certifi import ssl def create_ssl_context(custom_ca: Optional[str] = None) -> ssl.SSLContext: context = ssl.create_default_context() if custom_ca is None: # Use certifi's bundle ca_path: str = certifi.where() context.load_verify_locations(cafile=ca_path) else: context.load_verify_locations(cafile=custom_ca) return context ``` -------------------------------- ### httpx Library Integration (Sync and Async) Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md Shows how to configure both synchronous and asynchronous httpx clients to use Certifi's CA bundle for verification. The `verify` parameter is set to `certifi.where()`. ```python import httpx import certifi # Create client with custom CA bundle with httpx.Client(verify=certifi.where()) as client: response = client.get('https://api.example.com') print(response.json()) # Async variant import asyncio async def fetch(): async with httpx.AsyncClient(verify=certifi.where()) as client: response = await client.get('https://api.example.com') return response.json() # Run async result = asyncio.run(fetch()) ``` -------------------------------- ### Integration with wget Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Uses the `certifi` CLI to retrieve the CA bundle path and then passes it to `wget` using the `--ca-certificate` option for secure HTTPS downloads. ```bash # Use with wget CERT=$(python -m certifi) wget --ca-certificate="$CERT" https://api.example.com/file ``` -------------------------------- ### Create a Custom Bundle Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Extracts the default certifi bundle, appends custom certificates from a local file, and sets the `REQUESTS_CA_BUNDLE` environment variable to use the combined bundle. ```bash # Extract certifi bundle and add custom certificates python -m certifi --contents > /tmp/bundle.pem cat /path/to/custom/cert.pem >> /tmp/bundle.pem # Use the combined bundle export REQUESTS_CA_BUNDLE=/tmp/bundle.pem ``` -------------------------------- ### Use certifi.where() with Requests Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/README.md Example demonstrating how to use certifi.where() to specify the certificate bundle path for the requests library. ```python requests.get(url, verify=certifi.where()) ``` -------------------------------- ### Create Custom SSL Context with Certifi Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md Explains how to create a custom SSL context using Certifi's CA bundle and then customize its properties like hostname checking and verification mode. It also shows how to set minimum TLS versions. ```python import ssl import certifi # Create default context using certifi context = ssl.create_default_context(cafile=certifi.where()) # Customize the context context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED # Optional: Add additional settings context.minimum_version = ssl.TLSVersion.TLSv1_2 print(f"SSL/TLS Version Range: {context.minimum_version} - {context.maximum_version}") ``` -------------------------------- ### Get Certifi Path Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Retrieves the file path to the Mozilla root certificates bundle. This is useful for debugging or manual configuration. ```python import certifi import os try: path = certifi.where() if not os.path.exists(path): print("Error: Certificate file not found") else: print(f"Using: {path}") except Exception as e: print(f"Error accessing certifi: {e}") ``` -------------------------------- ### Get CA Bundle Contents Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Retrieve the CA bundle as a string. Use this when you need the certificate data directly in memory. ```python import certifi certs = certifi.contents() # Returns: Full PEM-formatted certificate data as string # Type: str # Use: When you need the certificate data directly in memory ``` -------------------------------- ### Resource Cleanup with atexit Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Shows how Certifi registers a cleanup function with `atexit` to ensure proper resource management upon process exit. ```python # Both implementations import atexit def exit_cacert_ctx() -> None: _CACERT_CTX.__exit__(None, None, None) # Registered on first where() call atexit.register(exit_cacert_ctx) ``` -------------------------------- ### User Migration: Identical Behavior Across Python Versions Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Demonstrates that Certifi's core functions work identically across Python 3.7 through 3.14+, requiring no action from users when upgrading Python. ```python # Works identically on Python 3.7 through 3.14+ import certifi path = certifi.where() contents = certifi.contents() ``` -------------------------------- ### Python Version Support for importlib.resources Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Illustrates how to check Python version to determine the appropriate API for `importlib.resources`, noting that both modern and legacy APIs provide identical functionality. ```python import sys if sys.version_info >= (3, 11): print("Using modern importlib.resources API") else: print("Using legacy importlib.resources API") # Both provide identical functionality ``` -------------------------------- ### Get CA Bundle Path Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Retrieve the file path to the CA bundle. Use this when a library expects a file path for certificate verification. ```python import certifi path = certifi.where() # Returns: "/usr/local/lib/python3.11/site-packages/certifi/cacert.pem" # Type: str # Use: Pass to libraries that accept a file path parameter ``` -------------------------------- ### Split Certificate Bundle using OpenSSL Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/certificate-bundle-format.md This bash script demonstrates how to split a certificate bundle file into individual certificate files using the `csplit` command. It also shows how to examine the details of a specific certificate using `openssl x509`. ```bash # Split bundle into individual files cd /path/to/certifi csplit -f cert_ -b "_%02d.pem" $(python -m certifi) '/-----END CERTIFICATE-----/+1' '{*}' # Examine a specific certificate openssl x509 -in cert_00.pem -text -noout # Get certificate info openssl x509 -in cert_00.pem -subject -issuer -noout ``` -------------------------------- ### Get CA Bundle Path Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Retrieves the filesystem path to the certifi CA bundle. Use this when you need to pass the path to other tools or libraries. ```bash $ python -m certifi /usr/local/lib/python3.11/site-packages/certifi/cacert.pem ``` -------------------------------- ### File Operations with Certifi Outputs Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/types.md Illustrates saving the CA bundle contents to a file and verifying the existence of the CA bundle path. ```python import certifi import os # Save contents to file with open("cacert.pem", "w") as f: f.write(certifi.contents()) # Verify path exists assert os.path.exists(certifi.where()) ``` -------------------------------- ### Run Certifi CLI Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/package-structure.md Execute the certifi package from the command line using the `-m` flag. Options like `--contents` can be used to display certificate data. ```bash # Run as module python -m certifi # With options python -m certifi --contents ``` -------------------------------- ### Get CA Bundle Path and Contents Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/types.md Retrieves the file path to the CA bundle and its contents. The path is a string, and the contents are also returned as a string. ```python ca_bundle_path: str = certifi.where() ca_certificates: str = certifi.contents() ``` -------------------------------- ### Integrate Certifi with urllib Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/README.md Create an SSL context using `ssl.create_default_context` with `cafile` set to `certifi.where()`, then use this context with `urllib.request.urlopen`. ```python import urllib.request import ssl import certifi context = ssl.create_default_context(cafile=certifi.where()) response = urllib.request.urlopen( 'https://api.example.com', context=context ) ``` -------------------------------- ### Create SSL Context with Certifi Trust Store Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/certificate-bundle-format.md Demonstrates how to create an SSL context in Python that uses certifi's CA bundle for certificate validation. This is crucial for establishing trusted connections to remote servers. ```python import ssl import certifi # Create SSL context with certifi's trust store context = ssl.create_default_context(cafile=certifi.where()) # When connecting to a server: # 1. Server presents its certificate chain # 2. Client validates chain ending in a root from cacert.pem # 3. Connection succeeds if chain is valid # 4. Connection fails if root not in cacert.pem ``` -------------------------------- ### Get CA Bundle Contents Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Prints the full contents of the CA bundle to standard output. Use this when you need the certificate data itself for processing or saving. ```bash $ python -m certifi --contents # Issuer: CN=Example Root CA O=Example Inc. # Subject: CN=Example Root CA O=Example Inc. # Label: "Example Root CA" -----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAJ... ... -----END CERTIFICATE----- # Issuer: CN=Another Root CA ... ``` -------------------------------- ### Get CA Bundle Contents Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/certifi-module.md Retrieves the full content of the `cacert.pem` file as a string. This is useful for parsing certificates or loading them directly into SSL contexts. ```python import certifi # Get the certificate bundle contents as a string cert_data = certifi.contents() # Check if specific certificate is present if "ISRG Root X1" in cert_data: print("ISRG Root X1 certificate is available") # Parse certificates from cryptography import x509 from cryptography.hazmat.backends import default_backend import re cert_pem = certifi.contents() # Split multiple certificates cert_blocks = re.findall( r'-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----', cert_pem, re.DOTALL ) for i, cert_block in enumerate(cert_blocks): cert_obj = x509.load_pem_x509_certificate( cert_block.encode(), default_backend() ) print(f"Certificate {i}: {cert_obj.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)[0].value}") # Use with ssl context import ssl context = ssl.create_default_context() context.load_verify_locations(cadata=certifi.contents()) ``` -------------------------------- ### Get CA Bundle Path Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/certifi-module.md Retrieves the filesystem path to the `cacert.pem` file. This path can be used with libraries that require explicit CA bundle verification. ```python import certifi import ssl # Get the path to the certificate bundle ca_bundle_path = certifi.where() print(ca_bundle_path) # Output: /usr/local/lib/python3.11/site-packages/certifi/cacert.pem # Use with requests library import requests response = requests.get('https://api.example.com', verify=certifi.where()) # Use with urllib import urllib.request context = ssl.create_default_context(cafile=certifi.where()) with urllib.request.urlopen('https://api.example.com', context=context) as response: data = response.read() # Use with aiohttp import aiohttp import asyncio async def fetch(): connector = aiohttp.TCPConnector(ssl_context=ssl.create_default_context(cafile=certifi.where())) async with aioiohttp.ClientSession(connector=connector) as session: async with session.get('https://api.example.com') as resp: return await resp.text() ``` -------------------------------- ### httplib2 Library Integration Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md Demonstrates using Certifi with the httplib2 library by specifying the CA certificate bundle path during HTTP object initialization. ```python import httplib2 import certifi # Create HTTP object with custom CA bundle http = httplib2.Http(ca_certs=certifi.where()) # Make request response, content = http.request('https://api.example.com') print(content) ``` -------------------------------- ### Use with httpx Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Configure httpx to use certifi's CA bundle for SSL verification by passing the path to the `verify` parameter. ```python import httpx import certifi with httpx.Client(verify=certifi.where()) as client: response = client.get('https://api.example.com') ``` -------------------------------- ### Check Certifi Status Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Prints detailed information about the installed certifi package, including version, file path, existence, size, and the number of certificates in the bundle. ```python import certifi import os print(f"Version: {certifi.__version__}") print(f"Path: {certifi.where()}") print(f"Exists: {os.path.exists(certifi.where())}") print(f"Size: {os.path.getsize(certifi.where())} bytes") contents = certifi.contents() print(f"Cert count: {contents.count('-----BEGIN CERTIFICATE-----')}") ``` -------------------------------- ### Python 3.7-3.10 Resource Access Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Demonstrates how to access resources using the `path` function in older Python versions. ```python from importlib.resources import path as get_path get_path("certifi", "cacert.pem") ``` -------------------------------- ### Python 3.11+ Implementation of where() and contents() Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md This code structure shows the implementation for Python 3.11 and later, using importlib.resources.files() and importlib.resources.as_file() for accessing the cacert.pem resource. ```python # Python 3.11+ (lines 14-47 of core.py) from importlib.resources import as_file, files _CACERT_CTX = None _CACERT_PATH = None def where() -> str: global _CACERT_CTX global _CACERT_PATH if _CACERT_PATH is None: _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem")) _CACERT_PATH = str(_CACERT_CTX.__enter__()) atexit.register(exit_cacert_ctx) return _CACERT_PATH def contents() -> str: return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii") ``` -------------------------------- ### Integration with curl Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Uses the `certifi` CLI to retrieve the CA bundle path and then passes it to `curl` using the `--cacert` option for secure HTTPS requests. ```bash # Use with curl CERT=$(python -m certifi) curl --cacert "$CERT" https://api.example.com/endpoint ``` -------------------------------- ### Compatible Type Hints in Certifi Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Illustrates the use of compatible type hints that work across Python 3.7 and later versions. ```python # Both implementations use compatible type hints def where() -> str: # Works in Python 3.7+ def contents() -> str: # Works in Python 3.7+ ``` -------------------------------- ### Get CA Bundle Path (Python 3.11+) Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/core-module.md Retrieves the filesystem path to the bundled cacert.pem file using modern importlib.resources. This path is cached after the first access. ```python from importlib.resources import as_file, files _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem")) _CACERT_PATH = str(_CACERT_CTX.__enter__()) ``` -------------------------------- ### Certifi Caching Strategy Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Illustrates the module-level globals used for caching resource paths across calls. ```python # Module-level globals (identical in both implementations) _CACERT_CTX = None # Holds context manager _CACERT_PATH = None # Holds cached path # On first where() call: # 1. Check if _CACERT_PATH is None # 2. If None, get resource and enter context # 3. Convert to string and store in _CACERT_PATH # 4. Register cleanup with atexit # 5. Return cached path on subsequent calls ``` -------------------------------- ### Factory Pattern for SSL Context Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md A factory function that creates and returns an SSL context configured with certifi's root certificates. Useful for consistent SSL setup. ```python import certifi import ssl def create_ssl_context(): """Factory for SSL context.""" return ssl.create_default_context(cafile=certifi.where()) # Use context = create_ssl_context() ``` -------------------------------- ### Contents Output Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Outputs the PEM-formatted certificate bundle. This includes metadata for each certificate and the Base64-encoded certificate data. A trailing newline is added by `print()`. ```bash python -m certifi --contents ``` -------------------------------- ### Python Script: Running Certifi CLI Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Illustrates how to execute the certifi CLI from within a Python script using the `subprocess` module to capture its output (path or contents). ```python import subprocess # Get the path result = subprocess.run([ 'python', '-m', 'certifi' ], capture_output=True, text=True) ca_bundle_path = result.stdout.strip() print(f"CA Bundle: {ca_bundle_path}") # Get the contents result = subprocess.run([ 'python', '-m', 'certifi', '--contents' ], capture_output=True, text=True) ca_bundle_contents = result.stdout print(f"Bundle size: {len(ca_bundle_contents)} bytes") ``` -------------------------------- ### Requests Library Integration Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md Demonstrates how to use Certifi with the Requests library for secure HTTP requests. Method 1 explicitly provides the CA bundle path, while Method 2 relies on Requests' default behavior of using Certifi. ```python import requests import certifi # Method 1: Using the path response = requests.get('https://api.example.com/endpoint', verify=certifi.where()) print(response.json()) # Method 2: Using requests defaults (automatic) # Requests uses certifi by default, no explicit call needed response = requests.get('https://api.example.com/endpoint') ``` -------------------------------- ### Type Checking with Certifi Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/quick-reference.md Demonstrates how to use type hints for certifi functions, ensuring type safety during development. ```python from typing import TYPE_CHECKING if TYPE_CHECKING: from certifi import where, contents # Type checker knows: # where() -> str # contents() -> str # At runtime: import certifi path: str = certifi.where() certs: str = certifi.contents() ``` -------------------------------- ### Conditional Import Pattern for importlib.resources Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Demonstrates the conditional import logic used in Certifi to adapt to different Python versions' `importlib.resources` APIs. ```python import sys if sys.version_info >= (3, 11): # Imports for Python 3.11+ from importlib.resources import as_file, files _CACERT_CTX = None _CACERT_PATH = None # Python 3.11+ implementations def where() -> str: ... def contents() -> str: ... else: # Imports for Python 3.7-3.10 from importlib.resources import path as get_path, read_text _CACERT_CTX = None _CACERT_PATH = None # Python 3.7-3.10 implementations def where() -> str: ... def contents() -> str: ... ``` -------------------------------- ### Bash Script: Get CA Bundle Path and Use Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/api-reference/cli.md Demonstrates how to capture the CA bundle path in a Bash variable and use it for setting environment variables or with tools like curl and wget. ```bash #!/bin/bash # Get the CA bundle path CA_BUNDLE=$(python -m certifi) echo "Using CA bundle at: $CA_BUNDLE" # Use in environment variable export REQUESTS_CA_BUNDLE=$(python -m certifi) python my_script.py # Use with curl curl --cacert $(python -m certifi) https://api.example.com # Use with wget wget --ca-certificate=$(python -m certifi) https://api.example.com/file ``` -------------------------------- ### Certifi core.py - Core Functionality Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/package-structure.md Implements the core logic for accessing the CA certificate bundle, including version-specific resource handling and caching. It provides functions to get the bundle's path or contents. ```python import sys import atexit if sys.version_info >= (3, 11): from importlib.resources.abc import Traversable from importlib.resources import files else: from importlib_resources.abc import Traversable from importlib_resources import files _CACERT_CTX = None _CACERT_PATH = None def where() -> str: """Return the path to the CA bundle.""" global _CACERT_PATH if _CACERT_PATH is None: _CACERT_PATH = str(files("certifi") / "cacert.pem") return _CACERT_PATH def contents() -> str: """Return the contents of the CA bundle.""" with open(where(), 'r', encoding='utf-8') as f: return f.read() def exit_cacert_ctx() -> None: global _CACERT_CTX if _CACERT_CTX: _CACERT_CTX.close() _CACERT_CTX = None atexit.register(exit_cacert_ctx) if sys.version_info < (3, 11): # Backport for older Python versions class _ZipPath(Traversable): def __init__(self, zip_path, name): self.zip_path = zip_path self.name = name def __truediv__(self, other): return _ZipPath(self.zip_path / other, self.name / other) def is_file(self): return True def is_dir(self): return False def read_bytes(self): with open(self.zip_path, 'rb') as f: return f.read() def read_text(self, encoding=None, errors=None): with open(self.zip_path, 'r', encoding=encoding, errors=errors) as f: return f.read() def iterdir(self): yield self def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): pass class _ZipFiles: def __init__(self, package_name): self.package_name = package_name def __truediv__(self, other): return _ZipPath(files(self.package_name) / other, other) files = _ZipFiles("certifi") _CACERT_CTX = files("certifi") / "cacert.pem" _CACERT_PATH = str(_CACERT_CTX) atexit.register(_CACERT_CTX.close) ``` -------------------------------- ### Python 3.11+ Resource Access Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Shows the modern approach to accessing resources using `files` and `joinpath` in Python 3.11 and later. ```python from importlib.resources import files files("certifi").joinpath("cacert.pem") ``` -------------------------------- ### Extract Serial Numbers from Certificate Bundle Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/certificate-bundle-format.md This Python script extracts all serial numbers from the certifi bundle. It uses regular expressions to find lines starting with '# Serial:' and prints the first few serial numbers found. ```python import certifi import re bundle = certifi.contents() # Find all serial numbers serials = re.findall(r'# Serial: (.*?)(?=\n)', bundle) print(f"Found {len(serials)} certificates") for serial in serials[:5]: print(f" Serial: {serial}") ``` -------------------------------- ### Load Custom CA Certificates with SSL Context Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/usage-examples.md Creates an SSL context that includes both certifi's default certificates and additional custom CA certificates loaded from a specified PEM file. ```python import ssl import certifi # Create a new SSL context with certifi context = ssl.create_default_context(cafile=certifi.where()) # Load additional certificates def add_custom_ca(context, ca_pem_path): """Add a custom CA certificate to the context.""" context.load_verify_locations(cafile=ca_pem_path) # Add custom CAs add_custom_ca(context, "/path/to/custom-ca.pem") print(f"CA certs loaded: {len(context.get_ca_certs())} certificates") ``` -------------------------------- ### Extract All Issuers from Certificate Bundle Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/certificate-bundle-format.md This Python script extracts all issuer names from the certifi bundle. It uses regular expressions to find lines starting with '# Issuer:' and prints a sorted list of unique issuers found. ```python import certifi import re bundle = certifi.contents() # Find all issuer lines issuers = re.findall(r'# Issuer: (.*?)(?=\n)', bundle) print(f"Found {len(issuers)} unique issuers") for issuer in sorted(set(issuers))[:10]: print(f" - {issuer}") ``` -------------------------------- ### Migration: Python 3.11+ Implementation for Maintainers Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Simplified implementation for maintainers if Python 3.7-3.10 support is dropped, utilizing Python 3.11+ APIs for cleaner code. ```python # Simplified to always use Python 3.11+ API from importlib.resources import as_file, files def where() -> str: global _CACERT_CTX, _CACERT_PATH if _CACERT_PATH is None: _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem")) _CACERT_PATH = str(_CACERT_CTX.__enter__()) atexit.register(exit_cacert_ctx) return _CACERT_PATH def contents() -> str: return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii") ``` -------------------------------- ### Certifi __main__.py - Command-Line Interface Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/package-structure.md Provides a command-line interface for interacting with the certifi package. It allows users to retrieve the path to the CA bundle or its contents directly from the shell. ```python import argparse from certifi import contents, where def main(): parser = argparse.ArgumentParser(description="Get CA cert bundle path or contents.") parser.add_argument("-c", "--contents", action="store_true", help="Output the CA cert bundle contents.") args = parser.parse_args() if args.contents: print(contents()) else: print(where()) if __name__ == "__main__": main() ``` -------------------------------- ### Python 3.11+ Resource Content Access Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/python-version-compatibility.md Demonstrates reading resource content using the `Traversable` interface in Python 3.11 and later. ```python from importlib.resources import files files("certifi").joinpath("cacert.pem").read_text(encoding="ascii") ``` -------------------------------- ### Conditional CA Bundle Path Source: https://github.com/certifi/python-certifi/blob/master/_autodocs/types.md Demonstrates an optional type hint for a CA bundle path that might be None based on a condition. ```python maybe_path: str | None = certifi.where() if some_condition else None ```