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

教程:在 Azure 应用服务中部署使用 PostgreSQL 的 Django Web 应用Tutorial: Deploy a Django web app with PostgreSQL in Azure App Service

本教程介绍如何将数据驱动的 Python Django Web 应用部署到 Azure 应用服务,并将其连接到 Azure Database for Postgres 数据库。This tutorial shows how to deploy a data-driven Python Django web app to Azure App Service and connect it to an Azure Database for Postgres database. 应用服务提供高度可缩放的、可自我修补的 Web 托管服务。App Service provides a highly scalable, self-patching web hosting service.

在本教程中,你将使用 Azure CLI 完成以下任务:In this tutorial, you use the Azure CLI to complete the following tasks:

  • 使用 Python 和 Azure CLI 设置初始环境Set up your initial environment with Python and the Azure CLI
  • 创建 Azure Database for PostgreSQL 数据库Create an Azure Database for PostgreSQL database
  • 将代码部署到 Azure 应用服务并连接到 PostgresDeploy code to Azure App Service and connect to Postgres
  • 更新代码并重新部署Update your code and redeploy
  • 查看诊断日志View diagnostic logs
  • 在 Azure 门户中管理 Web 应用Manage the web app in the Azure portal

设置初始环境Set up your initial environment

  1. 具有活动订阅的 Azure 帐户。Have an Azure account with an active subscription. 免费创建帐户Create an account for free.
  2. 安装 Python 3.6 或更高版本Install Python 3.6 or higher.
  3. 安装 Azure CLI 2.0.80 或更高版本,使用它可以在任何 shell 中运行命令来预配和配置 Azure 资源。Install the Azure CLI 2.0.80 or higher, with which you run commands in any shell to provision and configure Azure resources.

打开终端窗口并检查 Python 版本是否为 3.6 或更高版本:Open a terminal window and check your Python version is 3.6 or higher:

python3 --version

检查 Azure CLI 版本是否为 2.0.80 或更高版本:Check that your Azure CLI version is 2.0.80 or higher:

az --version

然后通过 CLI 登录到 Azure:Then sign in to Azure through the CLI:

az login

此命令将打开浏览器以获取凭据。This command opens a browser to gather your credentials. 命令完成后,会显示包含订阅相关信息的 JSON 输出。When the command finishes, it shows JSON output containing information about your subscriptions.

登录后,可以使用 Azure CLI 运行 Azure 命令,处理订阅中的资源。Once signed in, you can run Azure commands with the Azure CLI to work with resources in your subscription.

克隆或下载示例应用Clone or download the sample app

克隆示例存储库:Clone the sample repository:

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

然后转到该文件夹:Then go into that folder:

cd djangoapp

Djangoapp 示例包含数据驱动的 Django 投票应用,该应用是根据 Django 文档中的编写你的第一个 Django 应用创建的。The djangoapp sample contains the data-driven Django polls app you get by following Writing your first Django app in the Django documentation. 为便于参考,本文在此提供了已完成的应用。The completed app is provided here for your convenience.

示例还会修改为在应用服务等生产环境中运行:The sample is also modified to run in a production environment like App Service:

  • 生产设置位于“azuresite/production.py”文件中。Production settings are in the azuresite/production.py file. 开发详细信息位于“azuresite/settings.py”文件中。Development details are in azuresite/settings.py.
  • DJANGO_ENV 环境变量设置为“生产”时,应用将使用生产设置。The app uses production settings when the DJANGO_ENV environment variable is set to "production". 你将稍后在本教程中创建此环境变量以及用于 PostgreSQL 数据库配置的其他环境变量。You create this environment variable later in the tutorial along with others used for the PostgreSQL database configuration.

这些更改特定于将 Django 配置为在任何生产环境中运行,而不是特定于应用服务。These changes are specific to configuring Django to run in any production environment and aren't particular to App Service. 有关详细信息,请参阅 Django 部署清单For more information, see the Django deployment checklist.

在 Azure 中创建 Postgres 数据库Create Postgres database in Azure

安装适用于 Azure CLI 的 db-up 扩展:Install the db-up extension for the Azure CLI:

az extension add --name db-up

如果无法识别 az 命令,请确保按照设置初始环境中所述安装 Azure CLI。If the az command is not recognized, be sure you have the Azure CLI installed as described in Set up your initial environment.

然后使用 az postgres up 命令在 Azure 中创建 Postgres 数据库:Then create the Postgres database in Azure with the az postgres up command:

az postgres up --resource-group DjangoPostgres-tutorial-rg --location westus2 --sku-name B_Gen4_1 --server-name <postgre-server-name> --database-name pollsdb --admin-user <admin-username> --admin-password <admin-password> --ssl-enforcement Enabled
  • <postgres-server-name> 替换为在所有 Azure 中唯一的名称(服务器终结点是 https://\<postgres-server-name>.postgres.database.azure.com)。Replace <postgres-server-name> with a name that's unique across all Azure (the server endpoint is https://\<postgres-server-name>.postgres.database.azure.com). 良好的模式是结合使用公司名称和其他唯一值。A good pattern is to use a combination of your company name and another unique value.
  • 对于 <admin-username> 和 <admin-password>,请指定用来为此 Postgres 服务器创建管理员用户的凭据 。For <admin-username> and <admin-password>, specify credentials to create an administrator user for this Postgres server.
  • 此处使用的 B_Gen4_1(基本,第 4 代,1 核)定价层 成本最低。The B_Gen4_1 (Basic, Gen4, 1 core) pricing tier used here is the least expensive. 对于生产数据库,请省略 --sku-name 参数以改用 GP_Gen5_2(常规用途,第 5 代,2 核)层。For production databases, omit the --sku-name argument to use the GP_Gen5_2 (General Purpose, Gen 5, 2 cores) tier instead.

此命令将执行以下操作,可能需要花几分钟的时间:This command performs the following actions, which may take a few minutes:

  • 创建名为 DjangoPostgres-tutorial-rg资源组(如果尚未存在)。Create a resource group called DjangoPostgres-tutorial-rg, if it doesn't already exist.
  • 创建 Postgres 服务器。Create a Postgres server.
  • 使用唯一的用户名和密码创建默认的管理员帐户。Create a default administrator account with a unique user name and password. (若要指定自己的凭据,请通过 az postgres up 命令使用 --admin-user--admin-password 参数。)(To specify your own credentials, use the --admin-user and --admin-password arguments with the az postgres up command.)
  • 创建 pollsdb 数据库。Create a pollsdb database.
  • 支持从本地 IP 地址进行访问。Enable access from your local IP address.
  • 支持从 Azure 服务进行访问。Enable access from Azure services.
  • 创建有权访问 pollsdb 数据库的数据库用户。Create a database user with access to the pollsdb database.

可以使用其他 az postgrespsql 命令单独执行每个步骤,但 az postgres up 可以完成所有这些操作。You can do all the steps separately with other az postgres and psql commands, but az postgres up does all the steps together.

当该命令完成时,它会输出一个 JSON 对象,其中包含数据库的不同连接字符串以及服务器 URL、生成的用户名(例如“joyfulKoala@msdocs-djangodb-12345”)和 GUID 密码。When the command completes, it outputs a JSON object that contains different connection strings for the database along with the server URL, a generated user name (such as "joyfulKoala@msdocs-djangodb-12345"), and a GUID password. 将用户名和密码复制到临时文本文件,你需要在本教程稍后的内容中使用它们。Copy the user name and password to a temporary text file as you need them later in this tutorial.


-l <location-name> 可以设置为任一个 Azure 区域-l <location-name>, can be set to any one of the Azure regions. 可以使用 az account list-locations 命令获取可供你的订阅使用的区域。You can get the regions available to your subscription with the az account list-locations command. 对于生产应用,请将数据库和应用放置在同一位置。For production apps, put your database and your app in the same location.

将代码部署到 Azure 应用服务Deploy the code to Azure App Service

在本部分中,你将在应用服务应用中创建应用主机,将此应用连接到 Postgres 数据库,然后将代码部署到该主机。In this section, you create app host in App Service app, connect this app to the Postgres database, then deploy your code to that host.

创建应用服务应用Create the App Service app

在终端中,请确保位于包含应用代码的存储库根(djangoapp)。In the terminal, make sure you're in the repository root (djangoapp) that contains the app code.

使用 az webapp up 命令创建应用服务应用(主机进程):Create an App Service app (the host process) with the az webapp up command:

az webapp up --resource-group DjangoPostgres-tutorial-rg --location westus2 --plan DjangoPostgres-tutorial-plan --sku B1 --name <app-name>
  • 对于 --location 参数,请使用与上一部分中数据库相同的位置。For the --location argument, use the same location as you did for the database in the previous section.
  • <app-name> 替换为在整个 Azure 中唯一的名称(服务器终结点是 https://\<app-name>.azurewebsites.net)。Replace <app-name> with a unique name across all Azure (the server endpoint is https://\<app-name>.azurewebsites.net). <app-name> 允许的字符为 A-Z0-9-Allowed characters for <app-name> are A-Z, 0-9, and -. 良好的模式是结合使用公司名称和应用标识符。A good pattern is to use a combination of your company name and an app identifier.

此命令将执行以下操作,可能需要花几分钟的时间:This command performs the following actions, which may take a few minutes:

  • 创建资源组(如果尚未存在)。Create the resource group if it doesn't already exist. (在此命令中,你将使用之前在其中创建数据库的同一资源组。)(In this command you use the same resource group in which you created the database earlier.)
  • 在基本定价层 (B1) 中创建应用服务计划“DjangoPostgres-tutorial-plan”(如果不存在)。Create the App Service plan DjangoPostgres-tutorial-plan in the Basic pricing tier (B1), if it doesn't exist. --plan--sku 都是可选的。--plan and --sku are optional.
  • 创建应用服务应用(如果不存在)。Create the App Service app if it doesn't exist.
  • 为应用启用默认日志记录(如果尚未启用)。Enable default logging for the app, if not already enabled.
  • 在启用了生成自动化的情况下,使用 ZIP 部署上传存储库。Upload the repository using ZIP deployment with build automation enabled.

成功部署后,该命令会生成类似于以下示例的 JSON 输出:Upon successful deployment, the command generates JSON output like the following example:

示例 az webapp up 命令输出


许多 Azure CLI 命令将常见参数(例如资源组和应用服务计划的名称)缓存到文件“.azure/config”中。因此,不需要使用后面的命令指定所有相同的参数。Many Azure CLI commands cache common parameters, such as the name of the resource group and App Service plan, into the file .azure/config. As a result, you don't need to specify all the same parameter with later commands. 例如,若要在进行更改后重新部署应用,则无需任何参数即可再次运行 az webapp upFor example, to redeploy the app after making changes, you can just run az webapp up again without any parameters. 但是,来自 CLI 扩展的命令(如 az postgres up)目前不使用缓存,因此需要使用 az webapp up 在此处指定资源组和位置。Commands that come from CLI extensions, such as az postgres up, however, do not at present use the cache, which is why you needed to specify the resource group and location here with az webapp up.


如果在此时尝试访问应用的 URL,则会遇到错误“DisallowedHost at/”。If you attempt to visit the app's URL at this point, you encounter the error "DisallowedHost at /". 发生此错误的原因是你尚未将应用配置为使用前面讨论过的生产设置,你可以在以下部分中执行此操作。This error happens because you have not yet configured the app to use the production settings discussed earlier, which you do in the following section.

配置环境变量以连接数据库Configure environment variables to connect the database

将代码部署到应用服务后,下一步是将应用连接到 Azure 中的 Postgres 数据库。With the code now deployed to App Service, the next step is to connect the app to the Postgres database in Azure.

应用代码需要在多个环境变量中查找数据库信息。The app code expects to find database information in a number of environment variables. 若要在应用服务中设置环境变量,你需要使用 az webapp config appsettings set 命令创建“应用设置”。To set environment variables in App Service, you create "app settings" with the az webapp config appsettings set command.

az webapp config appsettings set --settings DJANGO_ENV="production" DBHOST="<postgres-server-name>.postgres.database.azure.com" DBNAME="pollsdb" DBUSER="<username>" DBPASS="<password>"
  • <postgres-server-name> 替换为之前通过 az postgres up 命令使用的名称。Replace <postgres-server-name> with the name you used earlier with the az postgres up command.
  • <username><password> 替换为命令也为你生成的凭据。Replace <username> and <password> with the credentials that the command also generated for you.
  • 资源组和应用名称是从“.azure/config”文件中的缓存值中提取的。The resource group and app name are drawn from the cached values in the .azure/config file.
  • 命令按应用代码的预期方式创建名为 DJANGO_ENVDBHOSTDBNAMEDBUSERDBPASS 的设置。The command creates settings named DJANGO_ENV, DBHOST, DBNAME, DBUSER, and DBPASS as expected by the app code.
  • 在 Python 代码中,可以使用 os.environ.get('DJANGO_ENV') 之类的语句来访问这些设置(作为环境变量)。In your Python code, you access these settings as environment variables with statements like os.environ.get('DJANGO_ENV'). 有关详细信息,请参阅访问环境变量For more information, see Access environment variables.

运行 Django 数据库迁移Run Django database migrations

Django 数据库迁移会确保 Azure 数据库上的 PostgreSQL 中的架构与代码中描述的架构相匹配。Django database migrations ensure that the schema in the PostgreSQL on Azure database match those described in your code.

  1. 通过导航至“https://<app-name>.scm.azurewebsites.net/webssh/host”在浏览器中打开 SSH 会话,并使用 Azure 帐户凭据(而不是数据库服务器凭据)登录。Open an SSH session in the browser by navigating to https://<app-name>.scm.azurewebsites.net/webssh/host and sign in with your Azure account credentials (not the database server credentials).

  2. 在 SSH 会话中运行以下命令(可以使用 Ctrl+Shift+V 粘贴命令) :In the SSH session, run the following commands (you can paste commands using Ctrl+Shift+V):

    cd site/wwwroot
    # Activate default virtual environment in App Service container
    source /antenv/bin/activate
    # Install packages
    pip install -r requirements.txt
    # Run database migrations
    python manage.py migrate
    # Create the super user (follow prompts)
    python manage.py createsuperuser
  3. createsuperuser 命令会提示输入超级用户凭据。The createsuperuser command prompts you for superuser credentials. 针对本教程,请使用默认的用户名 root,对于电子邮件地址,按 Enter 以留空,并输入 Pollsdb1 作为密码。For the purposes of this tutorial, use the default username root, press Enter for the email address to leave it blank, and enter Pollsdb1 for the password.

在应用中创建轮询问题Create a poll question in the app

  1. 在浏览器中打开 URL“http://<app-name>.azurewebsites.net”。In a browser, open the URL http://<app-name>.azurewebsites.net. 应用应显示消息“无可用轮询”,因为数据库中尚没有特定的轮询。The app should display the message "No polls are available" because there are no specific polls yet in the database.

  2. 浏览到“http://<app-name>.azurewebsites.net/admin”。使用上一节中的超级用户凭据登录(rootPollsdb1)。Browse to http://<app-name>.azurewebsites.net/admin. Sign in using superuser credentials from the previous section (root and Pollsdb1). 在“轮询”下,选择“问题”旁边的“添加”,创建一个包含一些选项的轮询问题 。Under Polls, select Add next to Questions and create a poll question with some choices.

  3. 再次浏览到“http://<app-name>.azurewebsites.net/”,确认现在是否向用户显示了问题。Browse again to http://<app-name>.azurewebsites.net/ to confirm that the questions are now presented to the user. 回答你希望如何在数据库中生成某些数据。Answer questions however you like to generate some data in the database.

祝贺你!Congratulations! 你将在适用于 Linux 的 Azure 应用服务中使用主动 Postgres 数据库运行 Python Django Web 应用。You're running a Python Django web app in Azure App Service for Linux, with an active Postgres database.


应用服务将通过在每个 manage.py startproject 默认创建的子文件夹中查找“wsgi.py”文件来检测 Django 项目。App Service detects a Django project by looking for a wsgi.py file in each subfolder, which manage.py startproject creates by default. 应用服务找到该文件后,就会加载 Django Web 应用。When App Service finds that file, it loads the Django web app. 有关详细信息,请参阅配置内置的 Python 映像For more information, see Configure built-in Python image.

进行代码更改并重新部署Make code changes and redeploy

在本部分中,你将对应用进行本地更改,并将代码重新部署到应用服务。In this section, you make local changes to the app and redeploy the code to App Service. 在此过程中,你将设置支持正在进行的工作的 Python 虚拟环境。In the process, you set up a Python virtual environment that supports ongoing work.

在本地运行应用Run the app locally

在终端窗口中运行以下命令。In a terminal window, run the following commands. 创建超级用户时,请确保遵循以下提示:Be sure to follow the prompts when creating the superuser:

# Configure the Python virtual environment
python3 -m venv venv
source venv/bin/activate

# Install packages
pip install -r requirements.txt
# Run Django migrations
python manage.py migrate
# Create Django superuser (follow prompts)
python manage.py createsuperuser
# Run the dev server
python manage.py runserver

完全加载 Web 应用后,Django 开发服务器会在以下消息中提供本地应用 URL:“在 启动开发服务器”。Once the web app is fully loaded, the Django development server provides the local app URL in the message, "Starting development server at 使用“CTRL BREAK”退出服务器。Quit the server with CTRL-BREAK".

示例 Django 开发服务器输出

在本地测试应用,步骤如下:Test the app locally with the following steps:

  1. 在浏览器中转到“http://localhost:8000”,应再次看到消息“无可用轮询”。Go to http://localhost:8000 in a browser, which should display the message "No polls are available".

  2. 转到“http://localhost:8000/admin”,使用之前创建的管理员用户登录。Go to http://localhost:8000/admin and sign in using the admin user you created previously. 在“轮询”下方再次选择“问题”旁边的“添加”,创建一个包含一些选项的轮询问题 。Under Polls, again select Add next to Questions and create a poll question with some choices.

  3. 再次转到“http://localhost:8000”,回答问题以测试应用。Go to http://localhost:8000 again and answer the question to test the app.

  4. 按 Ctrl+C 来停止 Django 服务器 。Stop the Django server by pressing Ctrl+C.

在本地运行时,应用将使用本地 Sqlite3 数据库,而不会影响生产数据库。When running locally, the app is using a local Sqlite3 database and doesn't interfere with your production database. 如果需要,还可以使用本地 PostgreSQL 数据库来更好地模拟生产环境。You can also use a local PostgreSQL database, if desired, to better simulate your production environment.

更新应用Update the app

polls/models.py 中,找到以 choice_text 开头的行,并将 max_length 参数更改为 100:In polls/models.py, locate the line that begins with choice_text and change the max_length parameter to 100:

# Find this lie of code and set max_length to 100 instead of 200
choice_text = models.CharField(max_length=100)

因为你更改了数据模型,所以请创建新的 Django 迁移并迁移数据库:Because you changed the data model, create a new Django migration and migrate the database:

python manage.py makemigrations
python manage.py migrate

再次使用 python manage.py runserver 运行开发服务器,并在“http://localhost:8000/admin”中测试该应用:Run the development server again with python manage.py runserver and test the app at to http://localhost:8000/admin:

使用 Ctrl +C 再次停止 Django Web 服务器 。Stop the Django web server again with Ctrl+C.

将代码重新部署到 AzureRedeploy the code to Azure

在存储库根目录中运行以下命令:Run the following command in the repository root:

az webapp up

此命令使用“.azure/config”文件中缓存的参数。This command uses the parameters cached in the .azure/config file. 由于应用服务检测到应用已存在,因此仅重新部署代码。Because App Service detects that the app already exists, it just redeploys the code.

在 Azure 中重新运行迁移Rerun migrations in Azure

由于对数据模型进行了更改,因此需要在应用服务中重新运行数据库迁移。Because you made changes to the data model, you need to rerun database migrations in App Service.

通过导航至“https://<app-name>.scm.azurewebsites.net/webssh/host”在浏览器中再次打开 SSH 会话。Open an SSH session again in the browser by navigating to https://<app-name>.scm.azurewebsites.net/webssh/host. 然后运行以下命令:Then run the following commands:

cd site/wwwroot

# Activate default virtual environment in App Service container
source /antenv/bin/activate
# Run database migrations
python manage.py migrate

在生产环境中查看应用Review app in production

浏览到“http://<app-name>.azurewebsites.net”并再次在生产中测试应用。Browse to http://<app-name>.azurewebsites.net and test the app again in production. (因为你只更改了数据库字段的长度,所以仅在创建问题时尝试输入较长的响应时,更改才会比较明显。)(Because you only changed the length of a database field, the change is only noticeable if you try to enter a longer response when creation a question.)

流式传输诊断日志Stream diagnostic logs

可以访问在 Azure 上托管应用的容器内部生成的控制台日志。You can access the console logs generated from inside the container that hosts the app on Azure.

运行以下 Azure CLI 命令查看日志流。Run the following Azure CLI command to see the log stream. 此命令使用“.azure/config”文件中缓存的参数。This command uses parameters cached in the .azure/config file.

az webapp log tail

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

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


也可通过浏览器在 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.

az webapp up 将为你启用默认日志记录。az webapp up turns on the default logging for you. 出于性能原因,此日志记录在一段时间后会自动禁用,但每次重新运行 az webapp up 时,它又会重新启用。For performance reasons, this logging turns itself off after some time, but turns back on each time you run az webapp up again. 若要手动启用此日志记录,请运行以下命令:To turn it on manually, run the following command:

az webapp log config --docker-container-logging filesystem

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

Azure 门户中,搜索应用名称并在结果中选择应用。In the Azure portal, search for the app name and select the app in the results.

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

默认情况下,门户会显示应用的“概述”页,该页面提供一般的性能视图。By default, the portal shows your app's Overview page, which provides a general performance view. 也可在此处执行基本的管理任务,例如浏览、停止、重启和删除。Here, you can also perform basic management tasks like browse, stop, 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

如果想要保留应用或者继续查看下一个教程,请直接跳到接下来的步骤If you'd like to keep the app or continue to the next tutorial, skip ahead to Next steps. 否则,若要避免产生持续的费用,你可以删除为本教程创建的资源组:Otherwise, to avoid incurring ongoing charges you can delete the resource group create for this tutorial:

az group delete

此命令使用 .azure/config 文件中缓存的资源组名称。The command uses the resource group name cached in the .azure/config file. 通过删除资源组,还可以解除分配并删除其中包含的所有资源。By deleting the resource group, you also deallocate and delete all the resources contained within it.

后续步骤Next steps

了解如何将自定义 DNS 名称映射到应用:Learn how to map a custom DNS name to your app:

了解应用服务如何运行 Python 应用:Learn how App Service runs a Python app: