示例:使用 Azure 库创建和部署 Web 应用
此示例演示如何使用 Python 脚本中的 Azure SDK 管理 库来创建 Web 应用并将其部署到 Azure 应用服务。 应用代码是从 GitHub 存储库部署的。
使用管理库(从 azure-mgmt
开始的命名空间(例如 azure-mgmt-web
),可以编写配置和部署程序以执行通过 Azure 门户、Azure CLI 或其他资源管理工具执行的相同任务。 有关示例,请参阅 快速入门:将 Python(Django 或 Flask)Web 应用部署到 Azure 应用服务。 (本文稍后会提供等效的 Azure CLI 命令。
本文中的所有命令在 Linux/macOS bash 和 Windows 命令行界面中的工作方式相同,除非另有说明。
1:设置本地开发环境
如果尚未安装,请设置可以运行此代码的环境。 下面是一些选项:
使用
venv
或所选工具配置 Python 虚拟环境。 可以在本地或 Azure Cloud Shell 中创建虚拟环境,并在其中运行代码。 请务必激活虚拟环境以开始使用它。使用 conda 环境。
在 Visual Studio Code 或 GitHub Codespaces中使用 开发容器。
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。
然后,使用分叉的 URL 创建名为 REPO_URL
的环境变量。 下一部分中的示例代码取决于以下环境变量:
4:编写代码以创建和部署 Web 应用
使用以下代码创建名为 provision_deploy_web_app.py 的 Python 文件。 注释说明代码的详细信息。 在运行脚本之前,请务必定义 REPO_URL
和 AZURE_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 应用进行身份验证。
代码中使用的类的参考链接
- AzureCliCredential (azure.identity)
- ResourceManagementClient (azure.mgmt.resource)
- WebSiteManagementClient (azure.mgmt.web import)
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!”。
如果未看到预期的输出,请等待几分钟,然后重试。
如果仍然看不到预期的输出,则:
- 转到 Azure 门户。
- 选择 资源组,找到创建的资源组。
- 选择资源组名称以查看其包含的资源。 具体而言,请验证是否存在应用服务计划和应用服务。
- 选择应用服务,然后选择 部署中心。
- 选择 日志 选项卡以查看部署日志。
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 应用名称(--name
选项)和资源组名称(--resource-group
选项)替换为脚本中使用的值。
若要从 Azure 门户部署代码,请执行以下作:
- 转到 Azure 门户。
- 选择 资源组,找到创建的资源组。
- 选择资源组名称以查看其包含的资源。 具体而言,请验证是否存在应用服务计划和应用服务。
- 选择应用服务,然后选择 部署中心。
- 在顶部菜单中,选择 同步 以部署您的代码。
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