Share via


如何設定適用於 Python 的 Azure SDK Proxy

如果您的組織需要使用 Proxy 伺服器來存取因特網資源,您必須使用 Proxy 伺服器資訊來設定環境變數,以使用適用於 Python 的 Azure SDK。 設定環境變數 (HTTP_PROXY 和 HTTPS_PROXY) 會導致適用於 Python 的 Azure SDK 在運行時間使用 Proxy 伺服器。

Proxy 伺服器 URL 的格式為 http[s]://[username:password@]<ip_address_or_domain>:<port>/ 選擇性使用者名稱和密碼組合。

接著,您可以使用環境變數全域設定 Proxy,或將名為 proxies 的自變數傳遞至個別用戶端建構函式或作業方法,以指定 Proxy。

全域設定

若要全域設定文本或應用程式的 Proxy,請使用伺服器 URL 來定義 HTTP_PROXYHTTPS_PROXY 環境變數。 這些變數適用於任何版本的 Azure 連結庫。 請注意, HTTPS_PROXY 這並不表示 HTTPS Proxy,而是要求的 https:// Proxy。

如果您將 參數 use_env_settings=False 傳遞至用戶端物件建構函式或作業方法,則會忽略這些環境變數。

從命令行設定

rem Non-authenticated HTTP server:
set HTTP_PROXY=http://10.10.1.10:1180

rem Authenticated HTTP server:
set HTTP_PROXY=http://username:password@10.10.1.10:1180

rem Non-authenticated HTTPS server:
set HTTPS_PROXY=http://10.10.1.10:1180

rem Authenticated HTTPS server:
set HTTPS_PROXY=http://username:password@10.10.1.10:1180

在 Python 程式代碼中設定

您可以使用環境變數來設定 Proxy 設定,而不需要自定義設定。

import os
os.environ["HTTP_PROXY"] = "http://10.10.1.10:1180"

# Alternate URL and variable forms:
# os.environ["HTTP_PROXY"] = "http://username:password@10.10.1.10:1180"
# os.environ["HTTPS_PROXY"] = "http://10.10.1.10:1180"
# os.environ["HTTPS_PROXY"] = "http://username:password@10.10.1.10:1180"

自訂設定

在 Python 程式代碼中設定每個客戶端或個別方法

針對自定義組態,您可以指定特定客戶端物件或作業方法的 Proxy。 使用名為 proxies的自變數指定 Proxy 伺服器。

例如,範例:使用 Azure 記憶體一文中的下列程式代碼會使用建構函式來指定具有使用者認證的 BlobClient HTTPS Proxy。 在此情況下,對象來自以 azure.core 為基礎的 azure.storage.blob 連結庫。

from azure.identity import DefaultAzureCredential

# Import the client object from the SDK library
from azure.storage.blob import BlobClient

credential = DefaultAzureCredential()

storage_url = "https://<storageaccountname>.blob.core.windows.net"

blob_client = BlobClient(storage_url, container_name="blob-container-01",
    blob_name="sample-blob.txt", credential=credential,
    proxies={ "https": "https://username:password@10.10.1.10:1180" }
)

# Other forms that the proxy URL might take:
# proxies={ "http": "http://10.10.1.10:1180" }
# proxies={ "http": "http://username:password@10.10.1.10:1180" }
# proxies={ "https": "https://10.10.1.10:1180" }