Skip to main content
The Center's Directory
Code examples

Use a proxy with Python Requests

Use requests to read environment variables, set HTTP proxies, timeout, and perform limited error handling.

Maintained by the ZZHTTP engineering teamUpdated September 20, 2026

Example of using the caller-side project self-managed requests Dependency. The account is closed. us.zzhttp.com:7878 The full proxy username and sub-username and password are read from the controlled environment.

Python requests

Python
import os
from urllib.parse import quote

import requests

proxy_username = quote(os.environ["PROXY_USERNAME"], safe="")
proxy_password = quote(os.environ["PROXY_PASSWORD"], safe="")
proxy_url = f"http://{proxy_username}:{proxy_password}@us.zzhttp.com:7878"
proxies = {"http": proxy_url, "https": proxy_url}

response = requests.get(
    "https://ipinfo.io/json",
    proxies=proxies,
    timeout=(10, 30),
)
response.raise_for_status()
print(response.json())

Dependencies and Configuration

  • Install and lock dependencies in the project virtual environment.
  • The proxy value does not enter the source code or mirror layer.

Request

  • Both HTTP and HTTPS targets use the same HTTP proxy URL.
  • Set the connection and read timeouts separately.

Error handling

  • Distinguish between agent errors, connection timeouts, and target statuses.
  • Only limited retries are performed on parity requests.

Verification steps

  1. Locking in a virtual environment requests Versions and injected through deployment systems PROXY_USERNAME and PROXY_PASSWORD.
  2. Run one agentless request to record local exports, then run the sample and read the response ip, country and region; Region results are from third-party databases.
  3. Simulates the wrong gateway port, wrong password and short timeout, respectively, to confirm that the exception type can be distinguished and the log does not contain the proxy dictionary.

Expected results

  • raise_for_status() Without exceptions, the proxy request returns an output that is different from the local public IP.
  • Invalid password requests.exceptions.ProxyError or equivalent 407 The response, the connection timeout, and the target HTTP error remain distinguishable.

Failure border

  • Missing environment variables are thrown before a network request is initiated KeyError This is not a proxy availability error.
  • The example covers only a single HTTP request. High concurrency, connection pools, retry, and power-equal boundaries should be designed business-specific.

Security

  • The exception log does not output the proxy dictionary.
  • The response body is recorded in the required fields.

Did this answer your question?

Feedback is used only to improve the public documentation and does not submit accounts or request information.