如何設定 Azure SDK for Python 的代理伺服器配置

你通常需要代理人,如果:

  • 你現在正處於企業防火牆後面。
  • 你的網路流量必須經過安全設備。
  • 你想使用自訂代理來進行除錯或路由。

如果你的組織需要代理伺服器來存取網際網路資源,在使用 Azure SDK for Python 之前,先設定一個包含代理伺服器資訊的環境變數。 當你設定 HTTP_PROXYHTTPS_PROXY 環境變數時,Python 的Azure SDK會在執行時使用代理伺服器。

代理伺服器的網址為 http[s]://[username:password@]<ip_address_or_domain>:<port>/,使用者名稱與密碼組合為可選。

你可以從你的 IT 或網路團隊、瀏覽器或網路工具取得代理資訊。

你可以透過環境變數全域配置代理伺服器。 你也可以透過傳遞一個名為 proxies的參數來設定個別客戶端建構子或操作方法的代理。

全球配置設定

若要全域性地為您的程式碼或應用程式設定代理伺服器,請定義 HTTP_PROXYHTTPS_PROXY 環境變數,並設置伺服器的 URL。 這些變數可以與任何版本的 Azure 程式庫一起使用。 請注意,這 HTTPS_PROXY 並不代表 HTTPS 代理。 它指定了用於 https:// 請求的代理伺服器。

如果你把 use_env_settings=False 參數傳給客戶端物件建構子或操作方法,SDK 會忽略這些環境變數。

從命令行設置

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 程式碼中

透過使用環境變數設定代理設定。 你不需要任何自訂設定。

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 程式碼為客戶端或方法設定代理

自訂設定時,請指定特定用戶端物件或操作方法的代理。 使用一個名為 proxies的參數。

例如,以下摘自文章 Example: use Azure storage 的程式碼,在 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" }