示例:使用 Azure 库创建和部署 Web 应用

此示例演示如何使用 Python 脚本中的 Azure SDK 管理库创建 Web 应用并将其部署到 Azure 应用服务,以及从 GitHub 存储库中提取的应用代码。

用于 Python 的 Azure SDK 包括管理库(以命名空间开头 azure-mgmt),可让你自动执行资源配置和部署,这类似于可以使用 Azure 门户、Azure CLI 或 ARM 模板执行的作。 有关示例,请参阅 快速入门:将 Python(Django 或 Flask)Web 应用部署到 Azure 应用服务

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. 选择资源组以查看其资源。 请确保它包括应用服务计划和应用服务。
  4. 选择 应用服务,然后转到 部署中心
  5. 打开 “日志 ”选项卡,检查部署日志中是否有任何错误或状态更新。

7:重新部署 Web 应用代码(可选)

该脚本提供用于托管你的 Web 应用的所有必要资源,并将部署源配置为使用手动集成的分支存储库。 通过手动集成,需要手动触发 Web 应用,以便从指定的存储库和分支拉取更新。

该脚本使用 WebSiteManagementClient.web_apps.sync_repository 方法触发 Web 应用从存储库拉取代码。 如果对代码进行了进一步更改,可以通过再次调用此 API 或使用其他 Azure 工具(如 Azure CLI 或 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. 选择资源组名称以查看其资源。 请确保它包括应用服务计划和应用服务。
  4. 选择 应用服务,然后转到 部署中心
  5. 在顶部菜单中,选择“ 同步 ”以触发代码的部署。

8:清理资源

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

除非在脚本中更改资源组名称(--resource-group 选项),否则无需更改资源组名称。

如果不再需要在此示例中创建的资源组,可以通过运行 az group delete 命令将其删除。 虽然资源组不会产生持续费用,但最好清理任何未使用的资源。 --no-wait使用参数立即将控制权返回到命令行,而无需等待删除完成。

还可以使用 ResourceManagementClient.resource_groups.begin_delete 该方法以编程方式删除资源组。

另请参阅