共用方式為


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

代理伺服器通常在以下情況下需要:

  • 你在企業防火牆的後面
  • 您的網路流量需要通過安全設備
  • 您想要使用自訂代理伺服器進行除錯或路由設定

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

代理伺服器 URL 的格式為 http[s]://[username:password@]<ip_address_or_domain>:<port>/,其中使用者名稱和密碼組合是可選的。

您可以從您的 IT/網路團隊、瀏覽器或網路工具中獲取代理資訊。

然後,您可以透過使用環境變數來全域配置代理伺服器,或者,您可以在個別的客戶端構造函數或操作方法中傳遞名為proxies的參數來指定代理伺服器。

全球配置設定

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

若在客戶端物件構造函數或操作方法中傳遞參數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 程式碼中

您可以使用環境變數來設定代理伺服器設定,無需自訂配置。

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的代理伺服器。

例如,範例 :使用 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" }