示例:使用 Azure 库创建和部署 Web 应用
此示例演示如何使用 Python 脚本中的 Azure SDK 管理库来创建 Web 应用并将其部署到Azure App 服务。 应用代码是从 GitHub 存储库部署的。
借助管理库(命名空间以 azure-mgmt
开头,例如 azure-mgmt-web
),可以编写配置和部署计划,以执行可通过 Azure 门户、Azure CLI 或其他资源管理工具执行的相同任务。 有关示例,请参阅快速入门:将 Python(Django 或 Flask)Web 应用部署到Azure App 服务。 (本文中的后面部分提供了等效的 Azure CLI 命令。)
除非另行说明,否则本文中的所有资源在 Linux/macOS bash 和 Windows 命令行界面上的工作方式相同。
1:设置本地开发环境
如果尚未安装,请设置可以运行此代码的环境。 提供以下选择:
配置 Python 虚拟环境。 可以在本地或 Azure Cloud Shell 中创建虚拟环境,并在其中运行代码。 请务必激活虚拟环境以开始使用它。
在 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。
然后创建一个名为 REPO_URL
且带有分支 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 门户。
- 选择 资源组,找到创建的资源组。
- 选择资源组名称以查看其包含的资源。 具体而言,请验证是否存在App 服务计划和App 服务。
- 选择App 服务,然后选择部署中心。
- 选择 “日志 ”选项卡以查看部署日志。
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
将 Web 应用名称(--name
选项)和资源组名称(--resource-group
选项)替换为脚本中使用的值。
从Azure 门户部署代码:
- 转到 Azure 门户。
- 选择 资源组,找到创建的资源组。
- 选择资源组名称以查看其包含的资源。 具体而言,请验证是否存在App 服务计划和App 服务。
- 选择App 服务,然后选择部署中心。
- 在顶部菜单中,选择“同步”以部署代码。
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
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈