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

此範例示範如何使用 Python 腳本中的 Azure SDK 管理連結庫來建立及部署 Web 應用程式以 Azure App 服務。 應用程式程式代碼是從 GitHub 存放庫部署。

使用管理連結庫(例如,命名空間開頭azure-mgmtazure-mgmt-web,例如 ),您可以撰寫設定和部署程式,以執行您可以透過 Azure 入口網站、Azure CLI 或其他資源管理工具執行的相同工作。 如需範例,請參閱快速入門:將 Python(Django 或 Flask) Web 應用程式部署至 Azure App 服務。 (本文稍後會提供對等的 Azure CLI 命令

本文中的所有命令在Linux/macOS bash和 Windows 命令殼層中都相同,除非另有說明。

1:設定本機開發環境

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

2:安裝必要的 Azure 連結庫套件

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

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

在啟動虛擬環境的終端機或命令提示字元中,安裝需求:

pip install -r requirements.txt

3:分支範例存放庫

請流覽 https://github.com/Azure-Samples/python-docs-hello-world 存放庫,並將存放庫派生到您自己的 GitHub 帳戶。 您將使用分叉,以確保您具有將存放庫部署至 Azure 的許可權。

Forking the sample repository on GitHub

然後使用分支的 URL 建立名為 REPO_URL 的環境變數。 下一節中的範例程式代碼取決於此環境變數:

set REPO_URL=<url_of_your_fork>
set 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 型驗證(using 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 應用程式名稱 (option) 和資源群組名稱 (--name--resource-groupoption) 取代為您在文稿中使用的值。 您應該在瀏覽器中看到 「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

將 Web 應用程式名稱 (option) 和資源群組名稱 (--name--resource-groupoption) 取代為您在文稿中使用的值。

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

  1. 前往 Azure 入口網站
  2. 選取 [資源群組],然後尋找您建立的資源群組。
  3. 選取資源組名以檢視它所包含的資源。 具體來說,請確認App Service方案和App Service。
  4. 選取 App Service,然後選取 [部署中心]。
  5. 在頂端功能表上,選取 [ 同步 ] 以部署您的程序代碼。

8:清除資源

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

如果您不需要保留在此範例中建立的資源群組,請執行 az group delete 命令。 資源群組不會在您的訂用帳戶中產生任何持續費用,但最好清除您未主動使用的任何群組。 自 --no-wait 變數可讓命令立即傳回,而不是等待作業完成。

您也可以使用 ResourceManagementClient.resource_groups.begin_delete 方法,從程式代碼中刪除資源群組。

如需參考:對等的 Azure CLI 命令

下列 Azure CLI 命令會完成與 Python 腳本相同的布建步驟:

rem Replace <your_github_user_name> with the account name of the fork.

set repoUrl=https://github.com/<your_github_user_name>/python-docs-hello-world
set appName=PythonAzureExample-WebApp-%random%

az group create -l centralus -n PythonAzureExample-WebApp-rg

az appservice plan create -n PythonAzureExample-WebApp-plan -g PythonAzureExample-WebApp-rg ^
     --is-linux --sku F1

echo Creating app: %appName%

az webapp create -g PythonAzureExample-WebApp-rg -n %appName% ^
    --plan PythonAzureExample-WebApp-plan --runtime "python|3.8"

rem You can use --deployment-source-url with the first create command. It is shown here
rem to match the sequence of the Python code.

az webapp create -n %appName% -g PythonAzureExample-WebApp-rg ^
    --plan PythonAzureExample-WebApp-plan --runtime "python|3.8" ^
    --deployment-source-url %repoUrl% 

rem The previous command sets up External Git deployment from the specified repository. This 
rem command triggers a pull from the repository.

az webapp deployment source sync --name %appName% --resource-group PythonAzureExample-WebApp-rg

另請參閱