Python proxy integration and examples

Updated on 2026-10-18 About 3 min read

Pass a MantaProxy configuration with each Python web or API request. This Requests example verifies one proxy first, then reuses the configuration for your application. It applies to this program and does not change your system proxy.

1. Prepare connection details and Python

In Static Proxy Management, click the exit IP to open its details and copy the connection host, port, proxy username and password. Start with Python 3. These commands create an isolated environment and install Requests with SOCKS support.

macOS / Linux

python3 -m venv .venv
.venv/bin/python -m pip install "requests[socks]"

Windows PowerShell

py -m venv .venv
.\.venv\Scripts\python.exe -m pip install "requests[socks]"

2. Configure HTTP or SOCKS5

Replace the three YOUR_PROXY placeholders below with details from the same resource. Run the example in that same terminal. Enter only an IP or hostname for the host, without a scheme, port or credentials. The script prompts separately for the password; typed characters are hidden.

macOS / Linux

export MANTA_PROXY_HOST="YOUR_PROXY_HOST"
export MANTA_PROXY_PORT="YOUR_PROXY_PORT"
export MANTA_PROXY_USERNAME="YOUR_PROXY_USERNAME"
export MANTA_PROXY_SCHEME="http"

Windows PowerShell

$env:MANTA_PROXY_HOST="YOUR_PROXY_HOST"
$env:MANTA_PROXY_PORT="YOUR_PROXY_PORT"
$env:MANTA_PROXY_USERNAME="YOUR_PROXY_USERNAME"
$env:MANTA_PROXY_SCHEME="http"

Keep MANTA_PROXY_SCHEME as http for an HTTP proxy, or change it to socks5h for SOCKS5. The http and https dictionary keys describe the destination, while their values use the proxy protocol. An HTTPS destination does not require changing an HTTP proxy URL to https://. socks5h resolves destination names through the proxy; socks5 resolves them locally.

Complete example: proxy_example.py

Save this as proxy_example.py, or download the file. Special characters in the username and password are URL-encoded automatically. The script prints the exit IP and does not log the complete proxy URL.

Download the complete Python example

"""Test one MantaProxy resource with Requests. Install: requests[socks]."""

import os
from getpass import getpass
from urllib.parse import quote

import requests


def build_proxies():
    required = ("MANTA_PROXY_HOST", "MANTA_PROXY_PORT", "MANTA_PROXY_USERNAME")
    missing = [name for name in required if not os.environ.get(name)]
    if missing:
        raise SystemExit("Set these variables first: " + ", ".join(missing))

    scheme = os.environ.get("MANTA_PROXY_SCHEME", "http").strip().lower()
    if scheme not in ("http", "socks5h"):
        raise SystemExit("MANTA_PROXY_SCHEME must be http or socks5h.")
    host = os.environ["MANTA_PROXY_HOST"].strip()
    if "://" in host or "/" in host or "@" in host:
        raise SystemExit("Use the host only, without a URL, port or credentials.")
    try:
        port = int(os.environ["MANTA_PROXY_PORT"])
        if not 1 <= port <= 65535:
            raise ValueError
    except ValueError:
        raise SystemExit("MANTA_PROXY_PORT must be a number from 1 to 65535.")

    username = os.environ["MANTA_PROXY_USERNAME"]
    password = os.environ.get("MANTA_PROXY_PASSWORD") or getpass("Proxy password: ")
    if not password:
        raise SystemExit("A proxy password is required.")
    if ":" in host and not host.startswith("["):
        host = "[" + host + "]"
    auth = quote(username, safe="") + ":" + quote(password, safe="")
    proxy_url = f"{scheme}://{auth}@{host}:{port}"
    return {"http": proxy_url, "https": proxy_url}


def main():
    proxies = build_proxies()
    with requests.Session() as session:
        session.trust_env = False
        try:
            response = session.get(
                "https://api.ipify.org?format=json",
                proxies=proxies,
                timeout=(10, 30),
            )
            response.raise_for_status()
            exit_ip = response.json()["ip"]
        except requests.exceptions.ProxyError:
            raise SystemExit("Proxy error: check host, port, protocol and credentials.")
        except requests.exceptions.Timeout:
            raise SystemExit("Timeout: check proxy reachability and the target site.")
        except requests.exceptions.SSLError:
            raise SystemExit("TLS error: check system time and trusted CA certificates.")
        except requests.exceptions.HTTPError as error:
            raise SystemExit(f"HTTP error: {error.response.status_code}")
        except requests.exceptions.RequestException:
            raise SystemExit("Request failed. Check the configuration and network.")
        except (ValueError, KeyError):
            raise SystemExit("The IP check did not return the expected JSON result.")
    print("Exit IP:", exit_ip)


if __name__ == "__main__":
    main()

trust_env=False keeps environment proxy settings out of this test, while HTTPS certificate verification stays enabled. If an organizational network requires a private CA, configure the trusted certificate path explicitly on the Session. A non-interactive service can inject MANTA_PROXY_PASSWORD through its secret-management mechanism; use the password prompt for local testing.

Reuse the configuration in your own request

Place the following code beside proxy_example.py and replace the destination with your own URL. Retain the exception handling from the complete example in your application. Requests returns HTTP responses and does not execute page JavaScript.

import requests
from proxy_example import build_proxies

with requests.Session() as session:
    session.trust_env = False
    response = session.get(
        "https://example.com/",
        proxies=build_proxies(),
        timeout=(10, 30),
    )
    response.raise_for_status()
    print(response.status_code)

3. Run the example and verify the exit

After setting the parameters, run from the directory containing the file:

macOS / Linux

.venv/bin/python proxy_example.py

Windows PowerShell

.\.venv\Scripts\python.exe proxy_example.py
  1. Enter the selected proxy’s password. Success prints Exit IP and the actual address. Documentation IPs are illustrative and cannot be used as connection details.
  2. Compare the result with the resource’s expected exit. Then test your actual destination with the same configuration; an IP check and successful application access are separate checks.
  3. timeout=(10, 30) sets connect and read timeouts, not a 30-second total deadline. Validate one resource and one request first, then adjust workload to your plan and destination requirements.

4. Troubleshooting

  • Missing MANTA_PROXY variables or an invalid port: Set variables in the same terminal that runs the script. Use the numeric resource port. Editors and scheduled jobs have their own environment and need these settings separately.
  • HTTP 407, authentication failure or Proxy error: Check the host, port, protocol and that resource’s proxy credentials. Do not use your website password or another resource’s credentials. A 407 in an HTTPS tunnel can also surface as ProxyError.
  • Missing dependencies for SOCKS support: Install requests[socks] with the same Python interpreter that runs the script. Check that your IDE selects that virtual environment.
  • Connection timeout or Read timed out: Check resource validity and network access to the host and port, then test the destination. Increasing timeouts or retries alone does not identify the cause.
  • Certificate verification failed: Check system time, Python CA certificates and organizational network requirements. Supply a trusted CA file explicitly where needed. Do not use verify=False to fix authentication or connectivity.
  • The exit IP is unexpected: Confirm that the current script runs and passes proxies on the request. Verify the purchased resource, exit, region and destination access separately, and send redacted diagnostics to support.

5. Official documentation and related guides

Requests: proxies / SOCKS · Requests: timeouts / errors · Python: urllib.parse.quote

Continue reading: View and copy connection details · Protocol and configuration FAQ · Connection troubleshooting FAQ · Contact technical support

Was this article helpful?

Your feedback helps us improve our documentation.