how python requests library use system proxy automaticaly when a use v2ray(pac is key to ressolve)?

99 Views Asked by At

pac(proxy auto config),if proxy is enable i want use it automatically,pac is the key to solving the problem。

python requests requests library in terminal do not use system proxy,unless "export http_proxy=http://127.0.0.1:1087;export https_proxy=http://127.0.0.1:1087;export ALL_PROXY=socks5://127.0.0.1:1080"

now i have run "pyinstaller --windowed main.py" that package a app,but do not use system proxy automatically,

I want python's requests library use v2ray's proxy automatically

when is enable global proxy,I found that the environment variable doesn't have an http_proxy or https_proxy or ALL_PROXY.

It's hard coded, not so good. What I want is the browser effect, the browser can not access the site through the proxy access

import requests

proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'http://proxy.example.com:8080',
}

response = requests.get('http://example.com', proxies=proxies)

how to resolve it?

1

There are 1 best solutions below

3
Sienna Dragon On

You can use os module to load proxy infomation instead of hard coded.

import os
import requests

# Get proxy server information from environment variables
proxy_host = os.environ.get('HTTP_PROXY')  # or 'http_proxy' depending on your environment
proxy_port = os.environ.get('HTTP_PROXY_PORT')  # or 'http_proxy_port' depending on your environment

# If the proxy server requires authentication, also get the username and password from environment variables
proxy_username = os.environ.get('HTTP_PROXY_USERNAME')
proxy_password = os.environ.get('HTTP_PROXY_PASSWORD')

# Build the proxy dictionary
proxies = {
    'http': f'http://{proxy_username}:{proxy_password}@{proxy_host}:{proxy_port}' if proxy_username and proxy_password else f'http://{proxy_host}:{proxy_port}',
    'https': f'https://{proxy_username}:{proxy_password}@{proxy_host}:{proxy_port}' if proxy_username and proxy_password else f'https://{proxy_host}:{proxy_port}'
}

# Set the target URL
url = 'https://www.example.com'

# Send a GET request through the proxy server to the target URL
response = requests.get(url, proxies=proxies)

# Print the response content
print(response.text)

Remember set environment variables before running your script:

export HTTP_PROXY="your_proxy_host"
export HTTP_PROXY_PORT="your_proxy_port"
export HTTP_PROXY_USERNAME="your_username"
export HTTP_PROXY_PASSWORD="your_password"