共用方式為


範例:使用 Azure 連結庫來建立及部署 Web 應用程式

此範例示範如何使用 Python 腳本中的 Azure SDK 管理連結庫,建立 Web 應用程式並將其部署至 Azure App Service,以及從 GitHub 存放庫提取的應用程式程式代碼。

適用於 Python 的 Azure SDK 包含管理連結庫(開頭為 azure-mgmt的命名空間),可讓您自動化資源設定和部署,類似於您可以使用 Azure 入口網站、Azure CLI 或 ARM 範本執行的動作。 如需範例,請參閱 快速入門:將 Python (Django 或 Flask) Web 應用程式部署至 Azure App Service

1:設定本機開發環境

如果您尚未設定環境,您可以在其中執行此程序代碼。 以下是一些選項:

  • 使用 venv 或您選擇的工具設定 Python 虛擬環境。 若要開始使用虛擬環境,請務必加以啟用。 若要安裝 Python,請參閱 安裝 Python

    #!/bin/bash
    # Create a virtual environment
    python -m venv .venv
    # Activate the virtual environment
    source .venv/Scripts/activate # only required for Windows (Git Bash)
    
  • 使用 conda 的環境。 若要安裝 Conda,請參閱 安裝 Miniconda

  • Visual Studio CodeGitHub Codespaces中使用 開發容器

2:安裝必要的 Azure 程式庫套件

使用下列內容建立名為 requirements.txt 的檔案:

azure-mgmt-resource
azure-mgmt-web
azure-identity

在您的本機開發環境中,使用下列程式代碼安裝需求:

pip install -r requirements.txt

3:派生範例存放庫

  1. 請瀏覽 https://github.com/Azure-Samples/python-docs-hello-world 並將存放庫複製到您自己的 GitHub 帳戶中。 使用分支可確保您具有將應用程式部署至 Azure 的必要許可權。

    在 GitHub 上分岔範例存放庫

  2. 接下來,建立名為 REPO_URL 的環境變數,並將其設定為分支存放庫的URL。 下一節中的範例程式代碼需要此變數。

export REPO_URL=<url_of_your_fork>
export AZURE_SUBSCRIPTION_ID=<subscription_id>

4:撰寫程式代碼以建立及部署 Web 應用程式

建立名為 provision_deploy_web_app.py 的 Python 檔案,並新增下列程序代碼。 內嵌註釋會說明程式碼的每個部分的作用。 和 REPO_URLAZURE_SUBSCRIPTION_ID 環境變數應該已在上一個步驟中設定。

import random, os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.web import WebSiteManagementClient

# Acquire a credential object using CLI-based authentication.
credential = AzureCliCredential()

# Retrieve subscription ID from environment variable
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

# Constants we need in multiple places: the resource group name and the region
# in which we provision resources. You can change these values however you want.
RESOURCE_GROUP_NAME = 'PythonAzureExample-WebApp-rg'
LOCATION = "centralus"

# Step 1: Provision the resource group.
resource_client = ResourceManagementClient(credential, subscription_id)

rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME,
    { "location": LOCATION })

print(f"Provisioned resource group {rg_result.name}")

# For details on the previous code, see Example: Provision a resource group
# at https://docs.microsoft.com/azure/developer/python/azure-sdk-example-resource-group


#Step 2: Provision the App Service plan, which defines the underlying VM for the web app.

# Names for the App Service plan and App Service. We use a random number with the
# latter to create a reasonably unique name. If you've already provisioned a
# web app and need to re-run the script, set the WEB_APP_NAME environment 
# variable to that name instead.
SERVICE_PLAN_NAME = 'PythonAzureExample-WebApp-plan'
WEB_APP_NAME = os.environ.get("WEB_APP_NAME", f"PythonAzureExample-WebApp-{random.randint(1,100000):05}")

# Obtain the client object
app_service_client = WebSiteManagementClient(credential, subscription_id)

# Provision the plan; Linux is the default
poller = app_service_client.app_service_plans.begin_create_or_update(RESOURCE_GROUP_NAME,
    SERVICE_PLAN_NAME,
    {
        "location": LOCATION,
        "reserved": True,
        "sku" : {"name" : "B1"}
    }
)

plan_result = poller.result()

print(f"Provisioned App Service plan {plan_result.name}")


# Step 3: With the plan in place, provision the web app itself, which is the process that can host
# whatever code we want to deploy to it.

poller = app_service_client.web_apps.begin_create_or_update(RESOURCE_GROUP_NAME,
    WEB_APP_NAME,
    {
        "location": LOCATION,
        "server_farm_id": plan_result.id,
        "site_config": {
            "linux_fx_version": "python|3.8"
        }
    }
)

web_app_result = poller.result()

print(f"Provisioned web app {web_app_result.name} at {web_app_result.default_host_name}")

# Step 4: deploy code from a GitHub repository. For Python code, App Service on Linux runs
# the code inside a container that makes certain assumptions about the structure of the code.
# For more information, see How to configure Python apps,
# https://docs.microsoft.com/azure/app-service/containers/how-to-configure-python.
#
# The create_or_update_source_control method doesn't provision a web app. It only sets the
# source control configuration for the app. In this case we're simply pointing to
# a GitHub repository.
#
# You can call this method again to change the repo.

REPO_URL = os.environ["REPO_URL"]

poller = app_service_client.web_apps.begin_create_or_update_source_control(RESOURCE_GROUP_NAME,
    WEB_APP_NAME, 
    { 
        "location": "GitHub",
        "repo_url": REPO_URL,
        "branch": "master",
        "is_manual_integration": True
    }
)

sc_result = poller.result()

print(f"Set source control on web app to {sc_result.branch} branch of {sc_result.repo_url}")

# Step 5: Deploy the code using the repository and branch configured in the previous step.
#
# If you push subsequent code changes to the repo and branch, you must call this method again
# or use another Azure tool like the Azure CLI or Azure portal to redeploy. 
# Note: By default, the method returns None.

app_service_client.web_apps.sync_repository(RESOURCE_GROUP_NAME, WEB_APP_NAME)

print(f"Deploy code")

此程式代碼會使用 CLI 型驗證(使用 AzureCliCredential),因為它會示範您可能直接使用 Azure CLI 執行的動作。 在這兩種情況下,您都使用相同的身分識別進行驗證。 視您的環境而定,您可能需要先執行 az login 進行驗證。

若要在生產腳本中使用這類程式代碼(例如,若要自動化 VM 管理),請使用 DefaultAzureCredential (建議)搭配服務主體型方法,如 如何使用 Azure 服務驗證 Python 應用程式中所述。

5:執行腳本

python provision_deploy_web_app.py

6:驗證 Web 應用程式部署

若要檢視已部署的網站,請執行下列命令:

az webapp browse --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg

將 Web 應用程式名稱(--name)更換為腳本產生的值。 除非您在腳本中變更它,否則您不需要變更資源組名 (--resource-group)。 當您開啟網站時,您應該會看到 “Hello, World!” 在您的瀏覽器中。

小提示

如果您沒有看到預期的輸出,請稍候幾分鐘再試一次。

如果您仍然看不到預期的輸出:

  1. 移至 Azure 入口網站
  2. 流覽至 [資源群組],然後找出您所建立的資源群組。
  3. 選取資源群組以檢視其資源。 請確定它同時包含 App Service 訂閱方案和 App Service。
  4. 選取 [App Service],然後移至 [部署中心]。
  5. 開啟 [ 記錄 ] 索引標籤,以檢查部署記錄是否有任何錯誤或狀態更新。

7:重新部署 Web 應用程式程式代碼(選擇性)

腳本會布建所有必要資源來裝載 Web 應用程式,並使用手動整合來設定部署來源以使用分支存放庫。 透過手動整合,您必須手動觸發 Web 應用程式,以從指定的存放庫和分支提取更新。

腳本會使用 WebSiteManagementClient.web_apps.sync_repository 方法來觸發 Web 應用程式,從您的存放庫提取程式代碼。 如果您進一步變更程序代碼,您可以再次呼叫此 API,或使用 Azure CLI 或 Azure 入口網站等其他 Azure 工具重新部署。

您可以執行 az webapp deployment source sync 命令,使用 Azure CLI 重新部署程序代碼:

az webapp deployment source sync --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg

除非您在腳本中變更它,否則您不需要變更資源組名 (--resource-group)。

若要從 Azure 入口網站部署程式代碼:

  1. 移至 Azure 入口網站
  2. 流覽至 [資源群組],然後找出您所建立的資源群組。
  3. 選取資源組名以檢視其資源。 請確定它同時包含 App Service 訂閱方案和 App Service。
  4. 選取 [App Service],然後移至 [部署中心]。
  5. 在頂端功能表上,選取 [ 同步 ] 以觸發程式代碼的部署。

8:清除資源

az group delete --name PythonAzureExample-WebApp-rg --no-wait

除非您在文稿中變更資源組名(--resource-group 選項),否則您不需要變更資源組名。

如果您不再需要在此範例中建立的資源群組,您可以執行 az group delete 命令來刪除它。 雖然資源群組不會產生持續費用,但最好清除任何未使用的資源。 --no-wait使用 自變數立即將控制權傳回命令行,而不需要等待刪除完成。

您也可以使用 ResourceManagementClient.resource_groups.begin_delete 方法來以程式設計方式刪除資源群組。

另請參閱