您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:在 Azure 应用服务中使用 PostgreSQL 生成 Python (Django) Web 应用Tutorial: Build a Python (Django) web app with PostgreSQL in Azure App Service

Linux 应用服务提供高度可缩放、自修补的 Web 托管服务。App Service on Linux provides a highly scalable, self-patching web hosting service. 本教程介绍如何创建一个数据驱动型 Python (Django) Web 应用,使用 PostgreSQL 作为数据库后端。This tutorial shows how to create a data-driven Python (Django) web app, using PostgreSQL as the database back-end. 完成后,会有一个在 Linux 上的 Azure 应用服务中运行的 Django Web 应用程序。When you are done, you have a Django web application running in Azure App Service on Linux.

Linux 上 Azure 应用服务中的 Python Django Web 应用

本教程介绍如何执行下列操作:In this tutorial, you learn how to:

  • 在 Azure 中创建 PostgreSQL 数据库Create a PostgreSQL database in Azure
  • 将 Python Web 应用连接到 PostgreSQLConnect a Python web app to PostgreSQL
  • 将 Python Web 应用部署到 AzureDeploy the Python web app to Azure
  • 查看诊断日志View diagnostic logs
  • 在 Azure 门户中管理 Python Web 应用Manage the Python web app in the Azure portal

备注

在创建 Azure Database for PostgreSQL 之前,请检查你所在地区中可用的计算代系Before creating an Azure Database for PostgreSQL, please check which compute generation is available in your region.

可以在 macOS 上执行本文中的步骤,Linux 和 Windows 说明在大多数情况下相同,本教程中并未详述差异。You can follow the steps in this article on macOS, Linux and Windows instructions are the same in most cases, but the differences are not detailed in this tutorial.

如果还没有 Azure 订阅,可以在开始前创建一个免费帐户If you don't have an Azure subscription, create a free account before you begin.

先决条件Prerequisites

完成本教程:To complete this tutorial:

  1. 安装 GitInstall Git
  2. 安装 PythonInstall Python
  3. 安装并运行 PostgreSQLInstall and run PostgreSQL

测试本地 PostgreSQL 安装并创建数据库Test local PostgreSQL installation and create a database

在本地终端窗口中运行 psql,以便连接到本地 PostgreSQL 服务器。In a local terminal window, run psql to connect to your local PostgreSQL server.

sudo -u postgres psql postgres

如果收到类似于unknown user: postgres的错误消息,则可能是因为 PostgreSQL 安装是使用登录的用户名配置的。If you get an error message similar to unknown user: postgres, your PostgreSQL installation may be configured with your logged in username. 改为尝试以下命令。Try the following command instead.

psql postgres

如果连接成功,则表示 PostgreSQL 数据库已在运行。If your connection is successful, your PostgreSQL database is running. 否则,请确保按照下载 - PostgreSQL Core Distribution 中针对操作系统的说明启动本地 PostgresQL 数据库。If not, make sure that your local PostgresQL database is started by following the instructions for your operating system at Downloads - PostgreSQL Core Distribution.

创建一个名为 pollsdb 的数据库,并设置一个名为 manager 的单独数据库用户,将其密码设置为supersecretpass 。Create a database called pollsdb and set up a separate database user named manager with password supersecretpass.

CREATE DATABASE pollsdb;
CREATE USER manager WITH PASSWORD 'supersecretpass';
GRANT ALL PRIVILEGES ON DATABASE pollsdb TO manager;

键入 \q 退出 PostgreSQL 客户端。Type \q to exit the PostgreSQL client.

创建本地 Python 应用Create local Python app

此步骤将设置本地 Python Django 项目。In this step, you set up the local Python Django project.

克隆示例应用Clone the sample app

打开终端窗口并 CD 到工作目录。Open the terminal window, and CD to a working directory.

运行下列命令以克隆示例存储库。Run the following commands to clone the sample repository.

git clone https://github.com/Azure-Samples/djangoapp.git
cd djangoapp

此示例存储库包含一个 Django 应用程序。This sample repository contains a Django application. 它是你通过 Django 文档中的入门教程获取的同一数据驱动型应用。It's the same data-driven app you would get by following the getting started tutorial in the Django documentation. 本教程不讲述 Django,而是介绍如何将 Django Web 应用(或其他数据驱动型 Python 应用)部署到 Azure 应用服务,然后再运行它。This tutorial doesn't teach you Django, but shows you how to take deploy and run a Django web app (or another data-driven Python app) to Azure App Service.

配置环境Configure environment

创建 Python 虚拟环境,并使用脚本来设置数据库连接设置。Create a Python virtual environment and use a script to set the database connection settings.

# Bash
python3 -m venv venv
source venv/bin/activate
source ./env.sh

# PowerShell
py -3 -m venv venv
venv\scripts\activate
.\env.ps1

env.shenv.ps1 中定义的环境变量可以在 azuresite/settings.py 中用来定义数据库设置。The environment variables defined in env.sh and env.ps1 are used in azuresite/settings.py to define the database settings.

在本地运行应用Run app locally

安装所需的包,运行 Django 迁移,然后创建管理员用户Install the required packages, run Django migrations and create an admin user.

pip install -r requirements.txt
python manage.py migrate
python manage.py createsuperuser

创建管理员用户以后,请运行 Django 服务器。Once the admin user is created, run the Django server.

python manage.py runserver

当 Django Web 应用完全加载后,将看到以下类似消息:When the Django web app is fully loaded, you see something similar to the following message:

Performing system checks...

System check identified no issues (0 silenced).
October 26, 2018 - 10:54:59
Django version 2.1.2, using settings 'azuresite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

在浏览器中转到 http://localhost:8000Go to http://localhost:8000 in a browser. 应该看到消息 No polls are available.You should see the message No polls are available..

转到 http://localhost:8000/admin,使用在上一步创建的管理员用户登录。Go to http://localhost:8000/admin and sign in using the admin user you created in the last step. 选择“问题”旁边的“添加”,创建一个包含一些选项的轮询问题。 Select Add next to Questions and create a poll question with some choices.

在应用程序服务中本地运行 Python Django 应用

再次转到 http://localhost:8000,此时会看到该轮询问题已显示。Go to http://localhost:8000 again and see the poll question displayed.

Django 示例应用程序在数据库中存储用户数据。The Django sample application stores user data in the database. 如果成功添加轮询问题,应用会将数据写入本地 PostgreSQL 数据库。If you are successful at adding a poll question, your app is writing data to the local PostgreSQL database.

若要随时停止 Django 服务器,请在终端中键入 Ctrl+C。To stop the Django server at anytime, type Ctrl+C in the terminal.

创建 PostgreSQL 生产数据库Create a production PostgreSQL database

此步骤在 Azure 中创建一个 PostgreSQL 数据库。In this step, you create a PostgreSQL database in Azure. 应用部署到 Azure 后,它将使用该云数据库。When your app is deployed to Azure, it uses this cloud database.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 可以将 Bash 或 PowerShell 与 Cloud Shell 配合使用来使用 Azure 服务。You can use either Bash or PowerShell with Cloud Shell to work with Azure services. 可以使用 Azure Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。You can use the Cloud Shell preinstalled commands to run the code in this article without having to install anything on your local environment.

若要启动 Azure Cloud Shell,请执行以下操作:To start Azure Cloud Shell:

选项Option 示例/链接Example/Link
选择代码块右上角的“试用”。 Select Try It in the upper-right corner of a code block. 选择“试用” 不会自动将代码复制到 Cloud Shell。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的“试用”示例
转到 https://shell.azure.com 或选择“启动 Cloud Shell” 按钮可在浏览器中打开 Cloud Shell。Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window
选择 Azure 门户右上方菜单栏中的“Cloud Shell” 按钮。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 门户中的“Cloud Shell”按钮

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:To run the code in this article in Azure Cloud Shell:

  1. 启动 Cloud Shell。Start Cloud Shell.

  2. 选择代码块上的“复制”按钮 以复制代码。Select the Copy button on a code block to copy the code.

  3. 在 Windows 和 Linux 上选择 Ctrl+Shift+V 将代码粘贴到 Cloud Shell 会话中,或在 macOS 上选择 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by selecting Cmd+Shift+V on macOS.

  4. 选择 Enter 运行此代码。Select Enter to run the code.

创建资源组Create a resource group

资源组是在其中部署和管理 Azure 资源(如 Web 应用、数据库和存储帐户)的逻辑容器。A resource group is a logical container into which Azure resources like web apps, databases, and storage accounts are deployed and managed. 例如,可以选择在使用完之后通过一个简单的步骤删除整个资源组。For example, you can choose to delete the entire resource group in one simple step later.

在 Cloud Shell 中,使用 az group create 命令创建资源组。In the Cloud Shell, create a resource group with the az group create command. 以下示例在“西欧” 位置创建名为“myResourceGroup” 的资源组。The following example creates a resource group named myResourceGroup in the West Europe location. 若要查看基本层中 Linux 上的应用服务支持的所有位置,请运行 az appservice list-locations --sku B1 --linux-workers-enabled 命令。To see all supported locations for App Service on Linux in Basic tier, run the az appservice list-locations --sku B1 --linux-workers-enabled command.

az group create --name myResourceGroup --location "West Europe"

通常在附近的区域中创建资源组和资源。You generally create your resource group and the resources in a region near you.

此命令完成后,JSON 输出会显示资源组属性。When the command finishes, a JSON output shows you the resource group properties.

创建 Azure Database for PostgreSQL 服务器Create an Azure Database for PostgreSQL server

在 Cloud Shell 中使用 az postgres server create 命令创建 PostgreSQL 服务器。Create a PostgreSQL server with the az postgres server create command in the Cloud Shell.

在以下示例命令中,请将 <postgresql-name> 替换为唯一的服务器名称,并将 <admin-username><admin-password> 替换为所需的用户凭据。In the following example command, replace <postgresql-name> with a unique server name, and replace <admin-username> and <admin-password> with the desired user credentials. 用户凭据用于数据库管理员帐户。The user credentials are for the database administrator account. 此服务器名称将用作 PostgreSQL 终结点 (https://<postgresql-name>.postgres.database.azure.com) 的一部分,因此需要在 Azure 中的所有服务器之间保持唯一。The server name is used as part of your PostgreSQL endpoint (https://<postgresql-name>.postgres.database.azure.com), so the name needs to be unique across all servers in Azure.

az postgres server create --resource-group myResourceGroup --name <postgresql-name> --location "West Europe" --admin-user <admin-username> --admin-password <admin-password> --sku-name B_Gen4_1

创建用于 PostgreSQL 的 Azure 数据库服务器后,Azure CLI 会显示类似于以下示例的信息:When the Azure Database for PostgreSQL server is created, the Azure CLI shows information similar to the following example:

{
  "administratorLogin": "<admin-username>",
  "fullyQualifiedDomainName": "<postgresql-name>.postgres.database.azure.com",
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.DBforPostgreSQL/servers/<postgresql-name>",
  "location": "westus",
  "name": "<postgresql-name>",
  "resourceGroup": "myResourceGroup",
  "sku": {
    "capacity": 1,
    "family": "Gen4",
    "name": "B_Gen4_1",
    "size": null,
    "tier": "Basic"
  },
  < JSON data removed for brevity. >
}

备注

记下 <admin-username> 和 <admin-password>,供以后使用。Remember <admin-username> and <admin-password> for later. 需要使用它们登录到 Postgre 服务器及其数据库。You need them to sign in to the Postgre server and its databases.

为 PostgreSQL 服务器创建防火墙规则Create firewall rules for the PostgreSQL server

在 Cloud Shell 中运行以下 Azure CLI 命令,以便从 Azure 资源访问数据库。In the Cloud Shell, run the following Azure CLI commands to allow access to the database from Azure resources.

az postgres server firewall-rule create --resource-group myResourceGroup --server-name <postgresql-name> --start-ip-address=0.0.0.0 --end-ip-address=0.0.0.0 --name AllowAllAzureIPs

备注

此设置允许从 Azure 网络中的所有 IP 进行网络连接。This setting allows network connections from all IPs within the Azure network. 进行生产性使用时,请尝试尽可能配置最严格的防火墙规则,即只使用应用所使用的出站 IP 地址For production use, try to configure the most restrictive firewall rules possible by using only the outbound IP addresses your app uses.

在 Cloud Shell 中再次运行该命令(将 <your-ip-address> 替换为你的本地 IPv4 IP 地址),以便从本地计算机进行访问。In the Cloud Shell, run the command again to allow access from your local computer by replacing <your-ip-address> with your local IPv4 IP address.

az postgres server firewall-rule create --resource-group myResourceGroup --server-name <postgresql-name> --start-ip-address=<your-ip-address> --end-ip-address=<your-ip-address> --name AllowLocalClient

将 Python 应用连接到生产数据库Connect Python app to production database

此步骤将 Django Web 应用连接到已创建的 Azure Database for PostgreSQL 服务器。In this step, you connect your Django web app to the Azure Database for PostgreSQL server you created.

创建空数据库和用户访问权限Create empty database and user access

在 Cloud Shell 中通过运行以下命令连接到数据库。In the Cloud Shell, connect to the database by running the command below. 系统提示输入管理员密码时,请使用在创建 Azure Database for PostgreSQL 服务器中指定的密码。When prompted for your admin password, use the same password you specified in Create an Azure Database for PostgreSQL server.

psql -h <postgresql-name>.postgres.database.azure.com -U <admin-username>@<postgresql-name> postgres

在 Azure Postgres 服务器中创建数据库和用户,就像在本地 Postgres 服务器中一样。Just like in your local Postgres server, create the database and user in the Azure Postgres server.

CREATE DATABASE pollsdb;
CREATE USER manager WITH PASSWORD 'supersecretpass';
GRANT ALL PRIVILEGES ON DATABASE pollsdb TO manager;

键入 \q 退出 PostgreSQL 客户端。Type \q to exit the PostgreSQL client.

备注

最佳做法是使用特定应用程序的受限权限而不是管理员用户来创建数据库用户。It's best practice to create database users with restricted permissions for specific applications, instead of using the admin user. 在此示例中,manager 用户只具有 pollsdb 数据库的完整权限。 In this example, the manager user has full privileges to only the pollsdb database.

测试从应用到生产数据库的连接Test app connectivity to production database

在本地终端窗口中,更改数据库环境变量(此前已通过运行 env.shenv.ps1 进行配置):In the local terminal window, change the database environment variables (which you configured earlier by running env.sh or env.ps1):

# Bash
export DBHOST="<postgresql-name>.postgres.database.azure.com"
export DBUSER="manager@<postgresql-name>"
export DBNAME="pollsdb"
export DBPASS="supersecretpass"

# PowerShell
$Env:DBHOST = "<postgresql-name>.postgres.database.azure.com"
$Env:DBUSER = "manager@<postgresql-name>"
$Env:DBNAME = "pollsdb"
$Env:DBPASS = "supersecretpass"

运行目标为 Azure 数据库的 Django 迁移,并创建管理员用户。Run Django migration to the Azure database and create an admin user.

python manage.py migrate
python manage.py createsuperuser

创建管理员用户以后,请运行 Django 服务器。Once the admin user is created, run the Django server.

python manage.py runserver

再次转到 http://localhost:8000Go to http://localhost:8000 in again. 应该会再次看到消息 No polls are available.You should see the message No polls are available. again.

转到 http://localhost:8000/admin,使用已创建的管理员用户登录,然后像以前一样创建轮询问题。Go to http://localhost:8000/admin and sign in using the admin user you created, and create a poll question like before.

在应用程序服务中本地运行 Python Django 应用

再次转到 http://localhost:8000,此时会看到该轮询问题已显示。Go to http://localhost:8000 again and see the poll question displayed. 现在,应用正将数据写入 Azure 中的数据库。Your app is now writing data to the database in Azure.

“部署到 Azure”Deploy to Azure

此步骤将已连接 Postgres 的 Python 应用程序部署到 Azure 应用服务。In this step, you deploy the Postgres-connected Python application to Azure App Service.

配置存储库Configure repository

Django 会验证传入请求中的 HTTP_HOST 标头。Django validates the HTTP_HOST header in incoming requests. 若要在应用服务中运行 Django Web 应用,需要将应用的完全限定域名添加到允许的主机中。For your Django web app to work in App Service, you need to add the full-qualified domain name of the app to the allowed hosts. 打开 azuresite/settings.py,找到 ALLOWED_HOSTS 设置。Open azuresite/settings.py and find the ALLOWED_HOSTS setting. 将行更改为:Change the line to:

ALLOWED_HOSTS = [os.environ['WEBSITE_SITE_NAME'] + '.azurewebsites.net', '127.0.0.1'] if 'WEBSITE_SITE_NAME' in os.environ else []

接下来,由于 Django 不支持在生产环境中处理静态文件,因此需手动完成相关的启用操作。Next, Django doesn't support serving static files in production, so you need to enable this manually. 在本教程中,请使用 WhiteNoiseFor this tutorial, you use WhiteNoise. WhiteNoise 包已经包括在 requirements.txt 中。The WhiteNoise package is already included in requirements.txt. 只需将 Django 配置为使用它即可。You just need to configure Django to use it.

azuresite/settings.py 中找到 MIDDLEWARE 设置,将 whitenoise.middleware.WhiteNoiseMiddleware 中间件添加到列表的 django.middleware.security.SecurityMiddleware 中间件下方。In azuresite/settings.py, find the MIDDLEWARE setting, and add the whitenoise.middleware.WhiteNoiseMiddleware middleware to the list, just below the django.middleware.security.SecurityMiddleware middleware. MIDDLEWARE 设置应该如下所示:Your MIDDLEWARE setting should look like this:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    ...
]

azuresite/settings.py 末尾添加以下行。At the end of azuresite/settings.py, add the following lines.

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

有关如何配置 WhiteNoise 的详细信息,请参阅 WhiteNoise 文档For more information on configuring WhiteNoise, see the WhiteNoise documentation.

重要

数据库设置部分已经遵循了有关如何使用环境变量的安全方面的最佳做法。The database settings section already follows the security best practice of using environment variables. 如需完整的部署建议,请参阅 Django 文档:部署清单For the complete deployment recommendations, see Django Documentation: deployment checklist.

将更改提交到存储库。Commit your changes into the repository.

git commit -am "configure for App Service"

配置部署用户Configure deployment user

可以使用“部署用户” 将 FTP 和本地 Git 部署到 Azure Web 应用。FTP and local Git can deploy to an Azure web app by using a deployment user. 配置部署用户之后,可对所有 Azure 部署使用此用户。Once you configure your deployment user, you can use it for all your Azure deployments. 帐户级部署用户名和密码不同于 Azure 订阅凭据。Your account-level deployment username and password are different from your Azure subscription credentials.

若要配置部署用户,请在 Azure Cloud Shell 中运行 az webapp deployment user set 命令。To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell. 将 <username> 和 <password> 替换为部署用户名和密码。Replace <username> and <password> with a deployment user username and password.

  • 用户名必须在 Azure 中唯一,并且为了本地 Git 推送,不能包含“@”符号。The username must be unique within Azure, and for local Git pushes, must not contain the ‘@’ symbol.
  • 密码必须至少为 8 个字符,且具有字母、数字和符号这三种元素中的两种。The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.
az webapp deployment user set --user-name <username> --password <password>

JSON 输出会将该密码显示为 nullThe JSON output shows the password as null. 如果收到 'Conflict'. Details: 409 错误,请更改用户名。If you get a 'Conflict'. Details: 409 error, change the username. 如果收到 'Bad Request'. Details: 400 错误,请使用更强的密码。If you get a 'Bad Request'. Details: 400 error, use a stronger password.

请记录你要用于部署 Web 应用的用户名和密码。Record your username and password to use to deploy your web apps.

创建应用服务计划Create App Service plan

在 Cloud Shell 中,使用 az appservice plan create 命令在资源组中创建应用服务计划。In the Cloud Shell, create an App Service plan in the resource group with the az appservice plan create command.

以下示例在基本定价层 (--sku B1) 和 Linux 容器 (--is-linux) 中创建名为 myAppServicePlan 的应用服务计划。The following example creates an App Service plan named myAppServicePlan in the Basic pricing tier (--sku B1) and in a Linux container (--is-linux).

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku B1 --is-linux

创建应用服务计划后,Azure CLI 会显示类似于以下示例的信息:When the App Service plan has been created, the Azure CLI shows information similar to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "West Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "linux",
  "location": "West Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

创建 Web 应用Create a web app

myAppServicePlan 应用服务计划中创建一个 Web 应用Create a web app in the myAppServicePlan App Service plan.

在 Cloud Shell 中可以使用 az webapp create 命令。In the Cloud Shell, you can use the az webapp create command. 在以下示例中,将 <app-name> 替换为全局唯一的应用名称(有效字符是 a-z0-9-)。In the following example, replace <app-name> with a globally unique app name (valid characters are a-z, 0-9, and -). 运行时设置为 PYTHON|3.7The runtime is set to PYTHON|3.7. 若要查看所有受支持的运行时,请运行 az webapp list-runtimes --linuxTo see all supported runtimes, run az webapp list-runtimes --linux.

# Bash
az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "PYTHON|3.7" --deployment-local-git
# PowerShell
az --% webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app-name> --runtime "PYTHON|3.7" --deployment-local-git

创建 Web 应用后,Azure CLI 会显示类似于以下示例的输出:When the web app has been created, the Azure CLI shows output similar to the following example:

Local git is configured with url of 'https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app-name>.azurewebsites.net",
  "deploymentLocalGitUrl": "https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

现在你已经创建了一个新的空 Web 应用并启用了 Git 部署。You’ve created an empty new web app, with git deployment enabled.

备注

Git 远程的 URL 将显示在 deploymentLocalGitUrl 属性中,其格式为 https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.gitThe URL of the Git remote is shown in the deploymentLocalGitUrl property, with the format https://<username>@<app-name>.scm.azurewebsites.net/<app-name>.git. 保存此 URL,因为后面需要它。Save this URL as you need it later.

配置环境变量Configure environment variables

在本教程的前面部分,你已定义用于连接到 PostgreSQL 数据库的环境变量。Earlier in the tutorial, you defined environment variables to connect to your PostgreSQL database.

在应用服务的 Cloud Shell 中,使用 az webapp config appsettings set 命令将环境变量设置为应用设置 。In App Service, you set environment variables as app settings by using the az webapp config appsettings set command in Cloud Shell.

以下示例将数据库连接详细信息指定为应用设置。The following example specifies the database connection details as app settings.

az webapp config appsettings set --name <app-name> --resource-group myResourceGroup --settings DBHOST="<postgresql-name>.postgres.database.azure.com" DBUSER="manager@<postgresql-name>" DBPASS="supersecretpass" DBNAME="pollsdb"

有关如何在代码中访问这些应用设置的信息,请参阅访问环境变量For information on how these app settings are accessed in your code, see Access environment variables.

从 Git 推送到 AzurePush to Azure from Git

回到本地终端窗口 ,将 Azure 远程功能添加到本地 Git 存储库。Back in the local terminal window, add an Azure remote to your local Git repository. <deploymentLocalGitUrl-from-create-step> 替换为从创建 Web 应用保存的 Git 远程 URL。Replace <deploymentLocalGitUrl-from-create-step> with the URL of the Git remote that you saved from Create a web app.

git remote add azure <deploymentLocalGitUrl-from-create-step>

使用以下命令推送到 Azure 远程功能以部署应用。Push to the Azure remote to deploy your app with the following command. 当 Git 凭据管理器提示输入凭据时,请确保输入在配置部署用户中创建的凭据,而不是用于登录到 Azure 门户的凭据。When prompted for credentials by Git Credential Manager, make sure that you enter the credentials you created in Configure a deployment user, not the credentials you use to sign in to the Azure portal.

git push azure master

此命令可能需要花费几分钟时间运行。This command may take a few minutes to run. 运行时,该命令会显示类似于以下示例的信息:While running, it displays information similar to the following example:

Counting objects: 7, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (7/7), 775 bytes | 0 bytes/s, done.
Total 7 (delta 4), reused 0 (delta 0)
remote: Updating branch 'master'.
remote: Updating submodules.
remote: Preparing deployment for commit id '6520eeafcc'.
remote: Generating deployment script.
remote: Running deployment command...
remote: Python deployment.
remote: Kudu sync from: '/home/site/repository' to: '/home/site/wwwroot'
. 
. 
. 
remote: Deployment successful.
remote: App container will begin restart within 10 seconds.
To https://<app-name>.scm.azurewebsites.net/<app-name>.git 
   06b6df4..6520eea  master -> master

应用服务部署服务器会看到存储库根目录中的 requirements.txt,并且会在 git push 后自动运行 Python 包管理。The App Service deployment server sees requirements.txt in the repository root and runs Python package management automatically after git push.

浏览到 Azure 应用Browse to the Azure app

浏览到已部署的应用。Browse to the deployed app. 它需要一些时间才能启动,因为在首次请求该应用时需下载并运行容器。It takes some time to start because the container needs to be downloaded and run when the app is requested for the first time. 如果页面超时或显示错误消息,请等待数分钟,然后刷新页面。If the page times out or displays an error message, wait a few minutes and refresh the page.

http://<app-name>.azurewebsites.net

你应该会看到此前创建的轮询问题。You should see the poll question that you created earlier.

应用服务会检测存储库中的 Django 项目,其方式是在每个由 manage.py startproject 默认创建的子目录中查找 wsgi.pyApp Service detects a Django project in your repository by looking for a wsgi.py in each subdirectory, which is created by manage.py startproject by default. 找到该文件后,就会加载 Django Web 应用。When it finds the file, it loads the Django web app. 若要详细了解应用服务如何加载 Python 应用,请参阅配置内置的 Python 映像For more information on how App Service loads Python apps, see Configure built-in Python image.

转到 <app-name>.azurewebsites.net,使用已创建的同一管理员用户登录。Go to <app-name>.azurewebsites.net and sign in using same admin user you created. 可以根据需要尝试创建更多的轮询问题。If you like, try creating some more poll questions.

在 Azure 的应用程序服务中运行 Python Django 应用

祝贺你! Congratulations! 你已在 Linux 的 Azure 应用服务中运行 Python (Django) Web 应用。You're running a Python (Django) web app in Azure App Service for Linux.

流式传输诊断日志Stream diagnostic logs

可以访问在容器中生成的控制台日志。You can access the console logs generated from inside the container. 首先,请在 Cloud Shell 中运行以下命令,以便启用容器日志记录功能:First, turn on container logging by running the following command in the Cloud Shell:

az webapp log config --name <app-name> --resource-group myResourceGroup --docker-container-logging filesystem

启用容器日志记录功能以后,请运行以下命令来查看日志流:Once container logging is turned on, run the following command to see the log stream:

az webapp log tail --name <app-name> --resource-group myResourceGroup

如果没有立即看到控制台日志,请在 30 秒后重新查看。If you don't see console logs immediately, check again in 30 seconds.

备注

也可通过浏览器在 https://<app-name>.scm.azurewebsites.net/api/logs/docker 中检查日志文件。You can also inspect the log files from the browser at https://<app-name>.scm.azurewebsites.net/api/logs/docker.

若要随时停止日志流式处理,请键入 Ctrl+CTo stop log streaming at any time, type Ctrl+C.

在 Azure 门户中管理应用Manage your app in the Azure portal

转到 Azure 门户查看创建的应用。Go to the Azure portal to see the app you created.

从左侧菜单中选择“应用程序服务”,并选择 Azure 应用的名称。 From the left menu, select App Services, then select the name of your Azure app.

在 Azure 门户中导航到 Python Django 应用

默认情况下,门户将显示应用的 “概述”页。By default, the portal shows your app's Overview page. 在此页中可以查看应用的运行状况。This page gives you a view of how your app is doing. 在此处还可以执行基本的管理任务,例如浏览、停止、启动、重新启动和删除。Here, you can also perform basic management tasks like browse, stop, start, restart, and delete. 该页左侧的选项卡显示可以打开的不同配置页。The tabs on the left side of the page show the different configuration pages you can open.

在 Azure 门户的“概述”页中管理 Python Django 应用

清理资源Clean up resources

在前面的步骤中,你在资源组中创建了 Azure 资源。In the preceding steps, you created Azure resources in a resource group. 如果认为将来不需要这些资源,请在 Cloud Shell 中运行以下命令删除资源组:If you don't expect to need these resources in the future, delete the resource group by running the following command in the Cloud Shell:

az group delete --name myResourceGroup

此命令可能需要花费一点时间运行。This command may take a minute to run.

后续步骤Next steps

本教程介绍了如何:In this tutorial, you learned how to:

  • 在 Azure 中创建 PostgreSQL 数据库Create a PostgreSQL database in Azure
  • 将 Python Web 应用连接到 PostgreSQLConnect a Python web app to PostgreSQL
  • 将 Python Web 应用部署到 AzureDeploy the Python web app to Azure
  • 查看诊断日志View diagnostic logs
  • 在 Azure 门户中管理 Python Web 应用Manage the Python web app in the Azure portal

继续学习下一篇教程,了解如何将自定义 DNS 名称映射到应用。Advance to the next tutorial to learn how to map a custom DNS name to your app.

或者,查看其他资源:Or, check out other resources: