教程:在 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 应用服务并连接到 PostgreSQLDeploy code to Azure App Service and connect to PostgreSQL
  • 更新代码并重新部署Update your code and redeploy
  • 查看诊断日志View diagnostic logs
  • 在 Azure 门户中管理 Web 应用Manage the web app in the Azure portal

1.设置初始环境1. Set up your initial environment

  1. 具有活动订阅的 Azure 帐户。Have an Azure account with an active subscription. 创建试用版订阅Create a Trial Subscription.
  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 cloud set -n AzureChinaCloud
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.

遇到问题?Having issues? 请告诉我们Let us know.

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

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

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

然后导航到该文件夹:Then navigate 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 settings are in azuresite/settings.py.
  • 当设置了 WEBSITE_HOSTNAME 环境变量时,应用将使用生产设置。The app uses production settings when the WEBSITE_HOSTNAME environment variable is set. Azure 应用服务会自动将此变量设置为 Web 应用的 URL,例如 msdocs-django.azurewebsites.netAzure App Service automatically sets this variable to the URL of the web app, such as msdocs-django.azurewebsites.net.

生产设置特定于将 Django 配置为在任何生产环境中运行,而不是特定于应用服务。The production settings 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 上 Django 的生产设置,以了解某些更改的详细信息。Also see Production settings for Django on Azure for details on some of the changes.

遇到问题?Having issues? 请告诉我们Let us know.

3.在 Azure 中创建 Postgres 数据库3. 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 chinaeast2 --sku-name B_Gen5_1 --server-name <postgres-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.chinacloudapi.cn)。Replace <postgres-server-name> with a name that's unique across all Azure (the server endpoint becomes https://<postgres-server-name>.postgres.database.chinacloudapi.cn). 良好的模式是结合使用公司名称和其他唯一值。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. 管理员用户名不能是 azure_superuser、azure_pg_admin、admin、administrator、root、guest 或 public 。The admin username can't be azure_superuser, azure_pg_admin, admin, administrator, root, guest, or public. 不能以 pg_ 开头。It can't start with pg_. 密码必须包含以下三个类别的 8 到 128 个字符:英文大写字母、英文小写字母、数字(0 到 9)和非字母数字字符(例如 !、#、%)。The password must contain 8 to 128 characters from three of the following categories: English uppercase letters, English lowercase letters, numbers (0 through 9), and non-alphanumeric characters (for example, !, #, %). 该密码不能包含用户名。The password cannot contain username.
  • 请勿在用户名或密码中使用 $ 字符。Do not use the $ character in the username or password. 稍后,将使用这些值创建环境变量,其中 $ 字符在用于运行 Python 应用的 Linux 容器中具有特殊含义。Later you create environment variables with these values where the $ character has special meaning within the Linux container used to run Python apps.
  • 此处使用的 B_Gen5_1(基本,第 5 代,1 核)定价层成本最低。The B_Gen5_1 (Basic, Gen5, 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.
  • 创建一个由 --server-name 参数命名的 Postgres 服务器。Create a Postgres server named by the --server-name argument.
  • 使用 --admin-user--admin-password 参数创建一个管理员帐户。Create an administrator account using the --admin-user and --admin-password arguments. 可以忽略这些参数,使命令为你生成唯一的凭据。You can omit these arguments to allow the command to generate unique credentials for you.
  • 创建一个由 --database-name 参数命名的 pollsdb 数据库。Create a pollsdb database as named by the --database-name argument.
  • 支持从本地 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.

遇到问题?Having issues? 请告诉我们Let us know.

4.将代码部署到 Azure 应用服务4. 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.

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

在终端中,请确保位于包含应用代码的“djangoapp”存储库文件夹中。In the terminal, make sure you're in the djangoapp repository folder 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 chinaeast2 --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>.chinacloudsites.cn)。Replace <app-name> with a unique name across all Azure (the server endpoint is https://\<app-name>.chinacloudsites.cn). <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.
  • 将常用参数(例如资源组和应用服务计划的名称)缓存到文件“.azure/config”中。因此,不需要使用后面的命令指定所有相同的参数。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 the initial use of az webapp up.

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

示例 az webapp up 命令输出

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

4.2 配置环境变量以连接数据库4.2 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.

应用代码预期在以下四个环境变量中查找数据库信息:DBHOSTDBNAMEDBUSERDBPASSThe app code expects to find database information in four environment variables named DBHOST, DBNAME, DBUSER, and DBPASS.

若要在应用服务中设置环境变量,请通过以下 az webapp config appsettings set 命令创建“应用设置”。To set environment variables in App Service, create "app settings" with the following az webapp config appsettings set command.

az webapp config appsettings set --settings DBHOST="<postgres-server-name>" 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. Azuresite/production.py 中的代码会自动追加 .postgres.database.chinacloudapi.cn 来创建完整的 Postgres 服务器 URL。The code in azuresite/production.py automatically appends .postgres.database.chinacloudapi.cn to create the full Postgres server URL.
  • 将 <username> 和 <password> 替换为你先前在 az postgres up 命令中使用的管理员凭据,或 az postgres up 为你生成的评估。Replace <username> and <password> with the administrator credentials that you used with the earlier az postgres up command, or those that az postgres up generated for you. azuresite/production.py 中的代码会自动通过 DBUSERDBHOST 构造完整的 Postgres 用户名,因此请勿包含 @server 部分。The code in azuresite/production.py automatically constructs the full Postgres username from DBUSER and DBHOST, so don't include the @server portion. (此外,如前所述,不应在任何一个值中使用 $ 字符,因为它对 Linux 环境变量具有特殊含义。)(Also, as noted earlier, you should not use the $ character in either value as it has a special meaning for Linux environment variables.)
  • 从 .azure/config 文件中的缓存值提取资源组和应用名称。The resource group and app names are drawn from the cached values in the .azure/config file.

在 Python 代码中,可以使用 os.environ.get('DBHOST') 之类的语句来访问这些设置(作为环境变量)。In your Python code, you access these settings as environment variables with statements like os.environ.get('DBHOST'). 有关详细信息,请参阅访问环境变量For more information, see Access environment variables.

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

4.3 运行 Django 数据库迁移4.3 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. 通过导航至以下 URL 并使用 Azure 帐户凭据(而不是数据库服务器凭据)登录来在浏览器中建立 SSH 会话。Open an SSH session in the browser by navigating to the following URL and signing in with your Azure account credentials (not the database server credentials).


    <app-name> 替换为之前在 az webapp up 命令中使用的名称。Replace <app-name> with the name used earlier in the az webapp up command.

    在 macOS 和 Linux 上,可以使用 az webapp ssh 命令以其他方式连接到 SSH 会话。On macOS and Linux, you can alternately connect to an SSH session with the az webapp ssh command.

    如果你无法连接到 SSH 会话,则表示应用本身已启动失败。If you cannot connect to the SSH session, then the app itself has failed to start. 请查看诊断日志以了解详细信息。Check the diagnostic logs for details. 例如,如果你没有在上一部分中创建必要的应用设置,则日志将指示 KeyError: 'DBNAME'For example, if you haven't created the necessary app settings in the previous section, the logs will indicate KeyError: 'DBNAME'.

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

    # Change to the app folder
    cd $APP_PATH
    # Activate the venv (requirements.txt is installed automatically)
    source /antenv/bin/activate
    # Run database migrations
    python manage.py migrate
    # Create the super user (follow prompts)
    python manage.py createsuperuser

    如果遇到与连接到数据库相关的任何错误,请检查在上一部分创建的应用程序设置的值。If you encounter any errors related to connecting to the database, check the values of the application settings created in the previous section.

  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.

  4. 如果看到“数据库已锁定”错误,请确保已在上一部分运行 az webapp settings 命令。If you see an error that the database is locked, make sure that you ran the az webapp settings command in the previous section. 如果没有这些设置,migrate 命令将无法与数据库通信,从而导致错误。Without those settings, the migrate command cannot communicate with the database, resulting in the error.

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

4.4 在应用中创建投票问题4.4 Create a poll question in the app

  1. 在浏览器中打开 URL http://<app-name>.chinacloudsites.cnIn a browser, open the URL http://<app-name>.chinacloudsites.cn. 应用应显示“投票应用”和“无可用投票”消息,这是因为数据库中尚无特定投票。The app should display the message "Polls app" and "No polls are available" because there are no specific polls yet in the database.

    如果看到“应用程序错误”,可能是由于你没有在上一步(配置环境变量以连接数据库)中创建所需的设置,或者这些值包含错误。If you see "Application Error", then it's likely that you either didn't create the required settings in the previous step, Configure environment variables to connect the database, or that those value contain errors. 运行命令 az webapp config appsettings list 以检查设置。Run the command az webapp config appsettings list to check the settings. 还可以检查诊断日志以查看应用启动过程中的特定错误。You can also check the diagnostic logs to see specific errors during app startup. 例如,如果你未创建设置,则日志将显示错误 KeyError: 'DBNAME'For example, if you didn't create the settings, the logs will show the error, KeyError: 'DBNAME'.

    更新设置以更正所有错误后,请等待应用重启,然后刷新浏览器。After updating the settings to correct any errors, give the app a minute to restart, then refresh the browser.

  2. 浏览到 http://<app-name>.chinacloudsites.cn/adminBrowse to http://<app-name>.chinacloudsites.cn/admin. 使用上一部分中的 Django 超级用户凭据登录(rootPollsdb1)。Sign in using Django 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>.chinacloudsites.cn,确认现在是否向用户显示了问题。Browse again to http://<app-name>.chinacloudsites.cn 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.

遇到问题?Having issues? 请告诉我们Let us know.


应用服务将通过在每个 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.

5.进行代码更改并重新部署5. 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.

5.1 在本地运行应用5.1 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 dependencies
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.

遇到问题?Having issues? 请告诉我们Let us know.

5.2 更新应用5.2 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 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.

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

5.3 将代码重新部署到 Azure5.3 Redeploy 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.

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

5.4 在 Azure 中重新运行迁移5.4 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.chinacloudsites.cn/webssh/host 再次建立 SSH 会话。Open an SSH session again in the browser by navigating to https://<app-name>.scm.chinacloudsites.cn/webssh/host. 然后运行以下命令:Then run the following commands:

source /antenv/bin/activate
python manage.py migrate

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

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

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

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

6.流式传输诊断日志6. 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.

遇到问题?Having issues? 请告诉我们Let us know.


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

7.在 Azure 门户中管理应用7. 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 应用

遇到问题?Having issues? 请先参阅故障排除指南,如果问题未能解决,请告诉我们Refer first to the Troubleshooting guide, otherwise, let us know.

8.清理资源8. Clean up resources

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

az group delete --no-wait

此命令使用 .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.

删除所有资源可能需要一些时间。Deleting all the resources can take some time. --no-wait 参数允许命令立即返回。The --no-wait argument allows the command to return immediately.

遇到问题?Having issues? 请告诉我们Let us know.

后续步骤Next steps

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

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