在 Azure App Service 中建置 Python 和 PostgreSQL 應用程式Build a Python and PostgreSQL app in Azure App Service

Linux 上的 App Service 提供可高度擴充、自我修復的 Web 主機服務。App Service on Linux provides a highly scalable, self-patching web hosting service. 本教學課程示範如何使用 PostgreSQL 作為資料庫後端,來建立資料驅動的 Python 應用程式。This tutorial shows how to create a data-driven Python app, using PostgreSQL as the database back end. 完成之後,您就會有在 Linux 上的 App Service 中執行的 Django 應用程式。When you are done, you have a Django application running in App Service on Linux.

Linux 上的 App Service 中的 Python Django 應用程式

在本教學課程中,您了解如何:In this tutorial, you learn how to:

  • 在 Azure 中建立 PostgreSQL 資料庫Create a PostgreSQL database in Azure
  • 將 Python 應用程式連線至 PostgreSQLConnect a Python app to PostgreSQL
  • 將應用程式部署至 AzureDeploy the app to Azure
  • 檢視診斷記錄View diagnostic logs
  • 在 Azure 入口網站中管理應用程式Manage the app in the Azure portal

注意

在建立適用於 PostgreSQL 的 Azure 資料庫之前,請先確認可在您的區域中產生的計算Before creating an Azure Database for PostgreSQL, please check which compute generation is available in your region.

您可以在 macOS 上依照本文中的步驟進行。You can follow the steps in this article on macOS. Linux 和 Windows 指示在大部分情況下都相同,本教學課程對差異不加詳述。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 資料庫已遵循 Downloads - 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,而是會說明如何對 App Service 部署和執行 Django 應用程式 (或另一個資料驅動的 Python 應用程式)。This tutorial doesn't teach you Django, but shows you how to take deploy and run a Django app (or another data-driven Python app) to 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.sh 和 env.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

當應用程式完全載入時,您會看到類似下列的訊息:When the 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:8000Navigate to http://localhost:8000 in a browser. 您應該會看見訊息 No polls are available.You should see the message No polls are available..

瀏覽至 http://localhost:8000/admin,然後使用您在上一個步驟中建立的管理使用者來登入。Navigate to http://localhost:8000/admin and sign in using the admin user you created in the last step. 按一下 [問題] 旁的 [新增],然後建立具有一些選擇的投票問題。Click Add next to Questions and create a poll question with some choices.

在本機執行的 Python Django 應用程式

再次瀏覽至 http://localhost:8000,然後查看所顯示的投票問題。Navigate 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 ShellOpen Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,並且會透過瀏覽器來使用。Azure Cloud Shell is an interactive shell environment hosted in Azure and used through your browse. Azure Cloud Shell 可讓您使用 bashPowerShell 殼層來執行各種可與 Azure 服務搭配運作的工具。Azure Cloud Shell allows you to use either bash or PowerShell shells to run a variety of tools to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文的內容,而不必在本機環境上安裝任何工具。Azure Cloud Shell comes pre-installed with the commands to allow you to run the content of this article without having to install anything on your local environment.

若要在 Azure Cloud Shell 上執行本文所包含的任何程式碼,請開啟 Cloud Shell 工作階段、使用某個程式碼區塊上的 [複製] 按鈕來複製程式碼,然後使用 Ctrl+Shift+V (在 Windows 和 Linux 上) 或 Cmd+Shift+V (在 macOS 上) 將程式碼貼到 Cloud Shell 工作階段中。To run any code contained in this article on Azure Cloud Shell, open a Cloud Shell session, use the Copy button on a code block to copy the code, and paste it into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS. 貼上的文字不會自動執行,因此請按 Enter 來執行程式碼。Pasted text is not automatically executed, so press Enter to run code.

您可以使用下列方式來啟動 Azure Cloud Shell:You can launch Azure Cloud Shell with:

選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 這__不會__自動將文字複製到 Cloud Shell。This doesn't automatically copy text to Cloud Shell. Azure Cloud Shell 的試試看範例
在瀏覽器中開啟 shell.azure.comOpen shell.azure.com in your browser. 啟動 Azure Cloud Shell 按鈕Launch Azure Cloud Shell button
選取 Azure 入口網站右上角功能表上的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the menu in the upper-right corner of the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

建立資源群組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 上之 App Service 的所有支援位置,請執行 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.

建立適用於 PostgreSQL 的 Azure 資料庫伺服器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 範例應用程式連線至您所建立的「適用於 PostgreSQL 的 Azure 資料庫」伺服器。In this step, you connect your Django sample 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. 在出現管理員密碼的提示時,請使用您在建立適用於 PostgreSQL 的 Azure 資料庫伺服器中指定的相同密碼。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

如同您的本機 Postgres 伺服器,在 Azure 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.sh 或 env.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"

將 Django 移轉至 Azure 資料庫,並建立管理使用者。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:8000Navigate to http://localhost:8000 in again. 您應該會再次看見訊息 No polls are available.You should see the message No polls are available. again.

瀏覽至 http://localhost:8000/admin,然後使用您建立的管理使用者登入,並建立如同前面的投票問題。Navigate 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,然後查看所顯示的投票問題。Navigate to http://localhost:8000 again and see the poll question displayed. 應用程式現在會將資料寫入 Azure 中的資料庫。Your app is now writing data to the database in Azure.

部署至 AzureDeploy to Azure

在此步驟中,您會將與 Postgres 連線的 Python 應用程式部署至 Azure App Service。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 應用程式在 App Service 中運作,您必須將應用程式的完整網域名稱新增至允許的主機。For your Django 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

在 Azure Cloud Shell 中,使用 az webapp deployment user set 命令來設定部署認證。In the Azure Cloud Shell, configure deployment credentials with the az webapp deployment user set command. 需要這個部署使用者,才能將 FTP 和本機 Git 部署至 Web 應用程式。This deployment user is required for FTP and local Git deployment to a web app. 使用者名稱和密碼是帳戶等級。The username and password are account level. 它們與您的 Azure 訂用帳戶認證不同。They're different from your Azure subscription credentials.

在下列範例中,請以新的使用者名稱和密碼取代 <username><password> (包括括弧)。In the following example, replace <username> and <password>, including the brackets, with a new username and password. 使用者名稱在 Azure 內必須是唯一的。The username must be unique within Azure. 密碼長度必須至少為 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>

您會獲得一個密碼顯示為 null 的 JSON 輸出。You get a JSON output with the password shown 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. 本機 Git 推送的部署使用者名稱不能包含 '@' 符號。The deployment username must not contain ‘@’ symbol for local Git pushes.

您只需設定此部署使用者一次。You configure this deployment user only once. 您可以將它用於所有 Azure 部署。You can use it for all your Azure deployments.

注意

請記錄使用者名稱和密碼。Record the username and password. 您稍後需要它們來部署 Web 應用程式。You need them to deploy the web app later.

建立 App Service 方案Create App Service plan

在 Cloud Shell 中,使用 az appservice plan create 命令在資源群組中建立 App Service 方案。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 的 App Service 方案。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

建立 App Service 方案後,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 App Service 方案中建立 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. 在下列範,了中,使用全域唯一的應用程式名稱 (有效的字元為 a-z0-9-) 取代 <app-name>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.

在 App Service 中,您可以在 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

App Service 部署伺服器會在存放庫的根目錄看到 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.

App Service 會藉由尋找每個子目錄中的 wsgi.py (預設會由 manage.py startproject 建立),來偵測存放庫中的 Django 專案。App 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 應用程式。When it finds the file, it loads the Django app. 如需 App Service 如何載入 Python 應用程式的詳細資訊,請參閱設定內建 Python 映像For more information on how App Service loads Python apps, see Configure built-in Python image.

瀏覽至 <app-name>.azurewebsites.net,然後使用您建立的同一個管理使用者來登入。Navigate to <app-name>.azurewebsites.net and sign in using same admin user you created. 如有需要,也可嘗試再建立一些投票問題。If you like, try creating some more poll questions.

在本機執行的 Python Django 應用程式

恭喜!Congratulations! 您正在適用於 Linux 的 App Service 中執行 Python 應用程式。You're running a Python app in 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, click App Services, then click the name of your Azure app.

入口網站瀏覽至 Azure 應用程式

根據預設,入口網站會顯示應用程式的 [概觀] 頁面。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 入口網站中的 App Service 頁面

清除資源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 應用程式連線至 PostgreSQLConnect a Python app to PostgreSQL
  • 將應用程式部署至 AzureDeploy the app to Azure
  • 檢視診斷記錄View diagnostic logs
  • 在 Azure 入口網站中管理應用程式Manage the 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: