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

快速入门:在 Linux 上的 Azure 应用服务中创建 Python 应用Quickstart: Create a Python app in Azure App Service on Linux

在本快速入门中,需将 Python Web 应用部署到 Linux 上的应用服务,该版本提供了一项高度可缩放、自我修补的 Azure Web 托管服务。In this quickstart, you deploy a Python web app to App Service on Linux, Azure's highly scalable, self-patching web hosting service. 在 Mac、Linux 或 Windows 计算机上,可使用本地 Azure 命令行界面 (CLI) 通过 Flask 或 Django 框架来部署示例。You use the local Azure command-line interface (CLI) on a Mac, Linux, or Windows computer to deploy a sample with either the Flask or Django frameworks. 配置的 Web 应用使用免费的应用服务层,因此本文中的操作不会产生任何费用。The web app you configure uses a free App Service tier, so you incur no costs in the course of this article.

提示

如果更喜欢使用 Visual Studio Code,请按照 Visual Studio Code 应用服务快速入门进行操作。If you prefer using Visual Studio Code instead, follow our Visual Studio Code App Service quickstart.

设置初始环境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.

存在问题?请告诉我们。Having issues? Let us know.

克隆示例Clone the sample

使用以下命令克隆示例存储库,并导航到示例文件夹。Clone the sample repository using the following command and navigate into the sample folder. (如果尚未安装 git,请安装 git。)(Install git if you don't have git already.)

git clone https://github.com/Azure-Samples/python-docs-hello-world

然后导航到该文件夹:Then navigate into that folder:

cd python-docs-hello-world
git clone https://github.com/Azure-Samples/python-docs-hello-django

然后导航到该文件夹:Then navigate into that folder:

cd python-docs-hello-django

示例包含 Azure 应用服务在启动应用时可以识别的框架特定代码。The sample contains framework-specific code that Azure App Service recognizes when starting the app. 有关详细信息,请参阅容器启动过程For more information, see Container startup process.

存在问题?请告诉我们。Having issues? Let us know.

运行示例Run the sample

  1. 确保位于 python-docs-hello-world 文件夹中。Make sure you're in the python-docs-hello-world folder.

  2. 创建虚拟环境并安装依赖项:Create a virtual environment and install dependencies:

    python3 -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
    

    如果遇到“[Errno 2] 没有此类文件或目录:“requirements.txt”。”,请确保位于 python-docs-hello-world 文件夹中。If you encounter "[Errno 2] No such file or directory: 'requirements.txt'.", make sure you're in the python-docs-hello-world folder.

  3. 运行开发服务器。Run the development server.

    flask run
    

    默认情况下,该服务器假定应用的条目模块位于示例使用的 app.py 中。By default, the server assumes that the app's entry module is in app.py, as used in the sample. (如果使用其他模块名称,请将 FLASK_APP 环境变量设置为该名称。)(If you use a different module name, set the FLASK_APP environment variable to that name.)

  4. 打开 Web 浏览器并转到 http://localhost:5000/ 处的示例应用。Open a web browser and go to the sample app at http://localhost:5000/. 该应用显示“Hello, World!”消息。The app displays the message Hello, World!.

    在本地运行示例 Python 应用

  5. 在终端窗口中,按 Ctrl+C 退出开发服务器 。In your terminal window, press Ctrl+C to exit the development server.

  1. 确保位于 python-docs-hello-django 文件夹中。Make sure you're in the python-docs-hello-django folder.

  2. 创建虚拟环境并安装依赖项:Create a virtual environment and install dependencies:

    python3 -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
    

    如果遇到“[Errno 2] 没有此类文件或目录:“requirements.txt”。”,请确保位于 python-docs-hello-django 文件夹中。If you encounter "[Errno 2] No such file or directory: 'requirements.txt'.", make sure you're in the python-docs-hello-django folder.

  3. 运行开发服务器。Run the development server.

    python manage.py runserver
    
  4. 打开 Web 浏览器并转到 http://localhost:8000/ 处的示例应用。Open a web browser and go to the sample app at http://localhost:8000/. 该应用显示“Hello, World!”消息。The app displays the message Hello, World!.

    在本地运行示例 Python 应用

  5. 在终端窗口中,按 Ctrl+C 退出开发服务器 。In your terminal window, press Ctrl+C to exit the development server.

存在问题?请告诉我们。Having issues? Let us know.

部署示例Deploy the sample

使用 az webapp up 命令在本地文件夹 (python-docs-hello-world) 中部署代码:Deploy the code in your local folder (python-docs-hello-world) using the az webapp up command:

az webapp up --sku F1 --name <app-name>
  • 如果无法识别 az 命令,请确保按照设置初始环境中所述安装 Azure CLI。If the az command isn't recognized, be sure you have the Azure CLI installed as described in Set up your initial environment.
  • 如果无法识别 webapp 命令,请确保 Azure CLI 版本为 2.0.80 或更高版本。If the webapp command isn't recognized, because that your Azure CLI version is 2.0.80 or higher. 如果不是,请安装最新版本If not, install the latest version.
  • <app_name> 替换为在整个 Azure 中均唯一的名称(有效字符为 a-z0-9-)。Replace <app_name> with a name that's unique across all of Azure (valid characters are a-z, 0-9, and -). 良好的模式是结合使用公司名称和应用标识符。A good pattern is to use a combination of your company name and an app identifier.
  • --sku F1 参数在“免费”定价层上创建 Web 应用。The --sku F1 argument creates the web app on the Free pricing tier. 省略此参数可使用更快的高级层,这会按小时计费。Omit this argument to use a faster premium tier, which incurs an hourly cost.
  • 可以选择包含参数 --location <location-name>,其中 <location_name> 是可用的 Azure 区域。You can optionally include the argument --location <location-name> where <location_name> is an available Azure region. 可以运行 az account list-locations 命令来检索 Azure 帐户的允许区域列表。You can retrieve a list of allowable regions for your Azure account by running the az account list-locations command.
  • 如果看到错误“无法自动检测应用的运行时堆栈”,请确保在包含 requirements.txt 文件的 python-docs-hello-world 文件夹 (Flask) 或 python-docs-hello-django 文件夹 (Django) 中运行该命令 。If you see the error, "Could not auto-detect the runtime stack of your app," make sure you're running the command in the python-docs-hello-world folder (Flask) or the python-docs-hello-django folder (Django) that contains the requirements.txt file. (请参阅通过 az webapp up 解决自动检测问题 (GitHub)。)(See Troubleshooting auto-detect issues with az webapp up (GitHub).)

此命令可能需要花费几分钟时间完成。The command may take a few minutes to complete. 运行时,它提供以下相关信息:创建资源组、应用服务计划和托管应用,配置日志记录,然后执行 ZIP 部署。While running, it provides messages about creating the resource group, the App Service plan and hosting app, configuring logging, then performing ZIP deployment. 然后,它将显示消息“可以在 http://<app-name>.azurewebsites.net(这是 Azure 上应用的 URL)启动应用”。It then gives the message, "You can launch the app at http://<app-name>.azurewebsites.net", which is the app's URL on Azure.

az webapp up 命令的示例输出

存在问题?请告诉我们。Having issues? Let us know.

备注

az webapp up 命令执行以下操作:The az webapp up command does the following actions:

浏览到应用Browse to the app

在 Web 浏览器中使用以下 URL 浏览到已部署的应用程序:http://<app-name>.azurewebsites.netBrowse to the deployed application in your web browser at the URL http://<app-name>.azurewebsites.net. 最初启动应用需要几分钟时间。It takes a few moments to start the app initially.

Python 示例代码在使用内置映像的应用服务中运行 Linux 容器。The Python sample code is running a Linux container in App Service using a built-in image.

在 Azure 中运行示例 Python 应用

祝贺你!Congratulations! 现已将 Python 应用部署到应用服务。You've deployed your Python app to App Service.

存在问题?请告诉我们。Having issues? Let us know.

重新部署更新Redeploy updates

在本部分中,你将对代码进行少量更改,然后将代码重新部署到 Azure。In this section, you make a small code change and then redeploy the code to Azure. 代码更改包括 print 语句,用于生成要在下一部分使用的日志记录输出。The code change includes a print statement to generate logging output that you work with in the next section.

在编辑器中打开 app.py,并更新 hello 函数以匹配以下代码。Open app.py in an editor and update the hello function to match the following code.

def hello():
    print("Handling request to home page.")
    return "Hello, Azure!"

在编辑器中打开 hello/views.py,并更新 hello 函数以匹配以下代码。Open hello/views.py in an editor and update the hello function to match the following code.

def hello(request):
    print("Handling request to home page.")
    return HttpResponse("Hello, Azure!")

保存更改,然后再次使用 az webapp up 命令重新部署应用:Save your changes, then redeploy the app using the az webapp up command again:

az webapp up

此命令使用本地缓存在 .azure/config 文件中的值,包括应用名称、资源组和应用服务计划。This command uses values that are cached locally in the .azure/config file, including the app name, resource group, and App Service plan.

部署完成后,切换回打开到 http://<app-name>.azurewebsites.net 的浏览器窗口。Once deployment is complete, switch back to the browser window open to http://<app-name>.azurewebsites.net. 刷新页面,刷新后的页面应显示修改后的消息:Refresh the page, which should display the modified message:

在 Azure 中运行更新的示例 Python 应用

存在问题?请告诉我们。Having issues? Let us know.

提示

Visual Studio Code 为 Python 和 Azure 应用服务提供了功能强大的扩展,简化了将 Python Web 应用部署到应用服务的过程。Visual Studio Code provides powerful extensions for Python and Azure App Service, which simplify the process of deploying Python web apps to App Service. 有关详细信息,请参阅将 Python 应用从 Visual Studio Code 部署到应用服务For more information, see Deploy Python apps to App Service from Visual Studio Code.

流式传输日志Stream logs

可以访问应用内和运行应用的容器所生成的控制台日志。You can access the console logs generated from inside the app and the container in which it runs. 这些日志包括使用 print 语句生成的任何输出。Logs include any output generated using print statements.

若要流式传输日志,请运行 az webapp log tail 命令:To stream logs, run the az webapp log tail command:

az webapp log tail

还可以在 az webapp up 命令中包含 --logs 参数,以在部署时自动打开日志流。You can also include the --logs parameter with then az webapp up command to automatically open the log stream on deployment.

在浏览器中刷新应用以生成控制台日志,其中包括描述对应用的 HTTP 请求的消息。Refresh the app in the browser to generate console logs, which include messages describing HTTP requests to the app. 如果未立即显示输出,请在 30 秒后重试。If no output appears immediately, try 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+C。To stop log streaming at any time, press Ctrl+C in the terminal.

存在问题?请告诉我们。Having issues? Let us know.

管理 Azure 应用Manage the Azure app

转到 Azure 门户管理已创建的应用。Go to the Azure portal to manage the app you created. 搜索并选择“应用服务”。Search for and select App Services.

在 Azure 门户中导航到应用服务

选择 Azure 应用名称。Select the name of your Azure app.

在 Azure 门户的应用程序服务中导航到 Python 应用

选择该应用将打开其“概述”页,你可以在其中执行基本的管理任务,例如浏览、停止、启动、重启和删除。Selecting the app opens its Overview page, where you can perform basic management tasks like browse, stop, start, restart, and delete.

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

应用服务菜单提供了用于配置应用的不同页面。The App Service menu provides different pages for configuring your app.

存在问题?请告诉我们。Having issues? Let us know.

清理资源Clean up resources

在前面的步骤中,你在资源组中创建了 Azure 资源。In the preceding steps, you created Azure resources in a resource group. 资源组根据位置得名,例如“appsvc_rg_Linux_CentralUS”。The resource group has a name like "appsvc_rg_Linux_CentralUS" depending on your location. 如果使用 F1 免费层以外的应用服务 SKU,这些资源会持续产生费用(请参阅应用服务定价)。If you use an App Service SKU other than the free F1 tier, these resources incur ongoing costs (see App Service pricing).

如果你认为将来不再需要这些资源,请运行以下命令删除资源组:If you don't expect to need these resources in the future, delete the resource group by running the following command:

az group delete --no-wait

此命令使用 .azure/config 文件中缓存的资源组名称。The command uses the resource group name cached in the .azure/config file.

--no-wait 参数允许此命令在操作完成之前返回。The --no-wait argument allows the command to return before the operation is complete.

存在问题?请告诉我们。Having issues? Let us know.

后续步骤Next steps