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

在 Azure 中创建 HTTP 触发的函数Create an HTTP triggered function in Azure


用于 Azure Functions 的 Python 当前为预览版。Python for Azure Functions is currently in preview. 若要接收重要更新,请订阅 GitHub 上的 Azure 应用服务公告存储库。To receive important updates, subscribe to the Azure App Service announcements repository on GitHub.

本文介绍如何使用命令行工具创建在 Azure Functions 中运行的 Python 项目。This article shows you how to use command-line tools to create a Python project that runs in Azure Functions. 你创建的此函数由 HTTP 请求触发。The function you create is triggered by HTTP requests. 最后,发布项目,在 Azure 中作为无服务器函数运行。Finally, you publish your project to run as a serverless function in Azure.

本文是 Azure Functions 的两个快速入门之一。This article is the first of two quickstarts for Azure Functions. 完成本文后,请将 Azure 存储队列输出绑定添加到你的函数。After you complete this article, you add an Azure Storage queue output binding to your function.


在开始之前,必须具有以下各项:Before you start, you must have the following:

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

创建并激活虚拟环境Create and activate a virtual environment

要本地开发和测试 Python 函数,必须在 Python 3.6 环境中工作。To locally develop and test Python functions, you must work in a Python 3.6 environment. 运行以下命令来创建并激活一个名为 .env 的虚拟环境。Run the following commands to create and activate a virtual environment named .env.

Bash 或终端窗口:Bash or a terminal window:

python3.6 -m venv .env
source .env/bin/activate

PowerShell 或 Windows 命令提示符:PowerShell or a Windows command prompt:

py -3.6 -m venv .env

剩下的命令在虚拟环境内运行。The remaining commands are run inside the virtual environment.

创建本地 Functions 项目Create a local Functions project

Functions 项目等效于 Azure 中的函数应用。A Functions project is the equivalent of a function app in Azure. 它可能具有多个函数,这些函数具有相同的本地和托管配置。It can have multiple functions that all share the same local and hosting configurations.

在虚拟环境中,运行以下命令,选择“python”作为工作器运行时 。In the virtual environment, run the following command, choosing python as your worker runtime.

func init MyFunctionProj

创建了名为 MyFunctionProj 的文件夹,该文件夹中包含以下三个文件 :A folder named MyFunctionProj is created, which contains the following three files:

  • local.settings.json 用于在本地运行时存储应用设置和连接字符串。local.settings.json is used to store app settings and connection strings when running locally. 此文件不会被发布到 Azure。This file doesn't get published to Azure.
  • requirements.txt 包含要在发布到 Azure 时安装的包列表。requirements.txt contains the list of packages to be installed on publishing to Azure.
  • host.json 包含在函数应用中影响所有函数的全局配置选项。host.json contains global configuration options that affect all functions in a function app. 此文件会被发布到 Azure。This file does get published to Azure.

导航到新的 MyFunctionProj 文件夹:Navigate to the new MyFunctionProj folder:

cd MyFunctionProj

接下来,请更新 host.json 文件以启用扩展捆绑包。Next, you update the host.json file to enable extension bundles.

引用绑定Reference bindings

扩展捆绑包可以更轻松地在以后添加绑定扩展。Extension bundles makes it easier to add binding extensions down the road. 它无需安装 .NET Core 2.x SDK。It also removes the requirement of installing the .NET Core 2.x SDK. 扩展捆绑包需要使用 Core Tools 的 2.6.1071 版或更高版本。Extension bundles requires version 2.6.1071 of the Core Tools, or a later version.

若要引用 Azure Functions 2.x 默认绑定,请打开 host.json 文件并更新内容以匹配以下代码。To reference the Azure Functions 2.x default bindings, open the host.json file and update contents to match the following code.

    "version": "2.0",
    "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[1.*, 2.0.0)"

现在,可以将函数添加到项目。Now, you can add a function to your project.

创建函数Create a function

若要将函数添加到项目中,请运行以下命令:To add a function to your project, run the following command:

func new

选择“HTTP 触发器” 模板,键入 HttpTrigger 作为函数名称,然后按 Enter。Choose the HTTP trigger template, type HttpTrigger as the name for the function, then press Enter.

创建了名为 HttpTrigger 的子文件夹,其中包含以下文件 :A subfolder named HttpTrigger is created, which contains the following files:

  • function.json: 定义函数、触发器和其他绑定的配置文件。function.json: configuration file that defines the function, trigger, and other bindings. 查看此文件,看到 scriptFile 的值指向包含函数的文件,而调用触发器和绑定在 bindings 数组中定义。Review this file and see that the value for scriptFile points to the file containing the function, while the invocation trigger and bindings are defined in the bindings array.

    每个绑定都需要一个方向、类型和唯一名称。Each binding requires a direction, type and a unique name. HTTP 触发器具有类型为 httpTrigger 的输入绑定和类型为 http 的输出绑定。The HTTP trigger has an input binding of type httpTrigger and output binding of type http.

  • __init__.py:作为 HTTP 触发函数的脚本文件。__init__.py: script file that is your HTTP triggered function. 查看此脚本,看到它包含默认值 main()Review this script and see that it contains a default main(). 触发器中的 HTTP 数据使用 req 命名绑定参数传递到此函数。HTTP data from the trigger is passed to this function using the req named binding parameter. 根据 function.json 中的定义,reqazure.functions.HttpRequest class 的一个实例。Defined in function.json, req is an instance of the azure.functions.HttpRequest class.

    在 function.json中定义为 $return 的返回对象是 azure.functions.HttpResponse class 的一个实例。The return object, defined as $return in function.json, is an instance of azure.functions.HttpResponse class. 要了解详细信息,请参阅 Azure Functions HTTP 触发器和绑定To learn more, see Azure Functions HTTP triggers and bindings.

在本地运行函数Run the function locally

以下命令启动函数应用,该应用使用 Azure 中相同的 Azure Functions 运行时本地运行。The following command starts the function app, which runs locally using the same Azure Functions runtime that is in Azure.

func host start

Functions 主机启动时,会写入类似于以下输出的内容。为了可读性,这些输出已经被截断:When the Functions host starts, it writes something like the following output, which has been truncated for readability:

            @   %%%%%%    @
          @@   %%%%%%      @@
       @@@    %%%%%%%%%%%    @@@
     @@      %%%%%%%%%%        @@
       @@         %%%%       @@
         @@      %%%       @@
           @@    %%      @@


Content root path: C:\functions\MyFunctionProj
Now listening on:
Application started. Press Ctrl+C to shut down.


Http Functions:

        HttpTrigger: http://localhost:7071/api/MyHttpTrigger

[8/27/2018 10:38:27 PM] Host started (29486ms)
[8/27/2018 10:38:27 PM] Job host started

从运行时输出中复制 HttpTrigger 函数的 URL,将其粘贴到浏览器的地址栏中。Copy the URL of your HttpTrigger function from the runtime output and paste it into your browser's address bar. 将查询字符串 ?name=<yourname> 追加到此 URL 并执行请求。Append the query string ?name=<yourname> to this URL and execute the request. 下面演示浏览器中本地函数返回的对 GET 请求的响应:The following shows the response in the browser to the GET request returned by the local function:


在本地运行函数以后,即可在 Azure 中创建函数应用和其他必需的资源。Now that you have run your function locally, you can create the function app and other required resources in Azure.

创建资源组Create a resource group

使用 az group create 创建资源组。Create a resource group with the az group create. Azure 资源组是在其中部署和管理 Azure 资源(例如函数应用、数据库和存储帐户)的逻辑容器。An Azure resource group is a logical container into which Azure resources like function apps, databases, and storage accounts are deployed and managed.

以下示例创建名为 myResourceGroup 的资源组。The following example creates a resource group named myResourceGroup.
如果不使用云 Shell,请先使用 az login 登录。If you are not using Cloud Shell, sign in first using az login.

az group create --name myResourceGroup --location westeurope

通常在附近的区域中创建资源组和资源。You generally create your resource group and the resources in a region near you. 若要查看应用服务计划的所有支持位置,请运行 az appservice list-locations 命令。To see all supported locations for App Service plans, run the az appservice list-locations command.

创建 Azure 存储帐户Create an Azure Storage account

Functions 使用通用帐户在 Azure 存储中保留状态以及有关函数的其他信息。Functions uses a general-purpose account in Azure Storage to maintain state and other information about your functions. 使用 az storage account create 命令在创建的资源组中创建通用存储帐户。Create a general-purpose storage account in the resource group you created by using the az storage account create command.

在以下命令中,请将 <storage_name> 占位符替换成全局唯一存储帐户名。In the following command, substitute a globally unique storage account name where you see the <storage_name> placeholder. 存储帐户名称必须为 3 到 24 个字符,并且只能包含数字和小写字母。Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only.

az storage account create --name <storage_name> --location westeurope --resource-group myResourceGroup --sku Standard_LRS

创建存储帐户后,Azure CLI 会显示类似于以下示例的信息:After the storage account has been created, the Azure CLI shows information similar to the following example:

  "creationTime": "2017-04-15T17:14:39.320307+00:00",
  "id": "/subscriptions/bbbef702-e769-477b-9f16-bc4d3aa97387/resourceGroups/myresourcegroup/...",
  "kind": "Storage",
  "location": "westeurope",
  "name": "myfunctionappstorage",
  "primaryEndpoints": {
    "blob": "https://myfunctionappstorage.blob.core.windows.net/",
    "file": "https://myfunctionappstorage.file.core.windows.net/",
    "queue": "https://myfunctionappstorage.queue.core.windows.net/",
    "table": "https://myfunctionappstorage.table.core.windows.net/"
    // Remaining output has been truncated for readability.

在 Azure 中创建一个函数应用Create a function app in Azure

函数应用提供了用于执行函数代码的环境。A function app provides an environment for executing your function code. 可以使用它将函数分组为一个逻辑单元,以便更轻松地管理、部署和共享资源。It lets you group functions as a logical unit for easier management, deployment, and sharing of resources.

运行以下命令,并使用唯一的函数应用名称替换 <APP_NAME> 占位符,使用存储帐户名称替换 <STORAGE_NAME>Run the following command using a unique function app name in place of the <APP_NAME> placeholder and the storage account name for <STORAGE_NAME>. <APP_NAME> 也是函数应用的默认 DNS 域。The <APP_NAME> is also the default DNS domain for the function app. 此名称在 Azure 的所有应用中必须独一无二。This name needs to be unique across all apps in Azure.

az functionapp create --resource-group myResourceGroup --os-type Linux \
--consumption-plan-location westeurope  --runtime python \
--name <APP_NAME> --storage-account  <STORAGE_NAME>


Azure Functions(适用于 Linux 的消耗计划)目前处于预览状态,仅可以下区域使用:美国西部、美国东部、西欧、东亚。Azure Functions, Consumption plan for Linux is currently in preview and only available on following regions: West US, East US, West Europe, East Asia. 此外,Linux 和 Windows 应用不能托管在同一个资源组中。Moreover, Linux and Windows apps cannot be hosted in the same resource group. 如果名为 myResourceGroup 的现有资源组有 Windows 函数应用或 Web 应用,必须使用其他资源组。If you have an existing resource group named myResourceGroup with a Windows function app or web app, you must use a different resource group.

现在,可以将本地函数项目发布到 Azure 中的函数应用了。You're now ready to publish your local functions project to the function app in Azure.

将函数应用项目部署到 AzureDeploy the function app project to Azure

在 Azure 中创建函数应用后,可以使用 func azure functionapp publish Core Tools 命令将项目代码部署到 Azure。After the function app is created in Azure, you can use the func azure functionapp publish Core Tools command to deploy your project code to Azure. 在下面的命令中,将 <APP_NAME> 替换为上一步中你的应用的名称。In the following command, replace <APP_NAME> with the name of your app from the previous step.

func azure functionapp publish <APP_NAME>

你将看到类似于以下内容的输出,为了提高可读性,已经截断了这些输出。You will see output similar to the following, which has been truncated for readability.

Getting site publishing info...

Preparing archive...
Uploading content...
Upload completed successfully.
Deployment completed successfully.
Syncing triggers...
Functions in myfunctionapp:
    HttpTrigger - [httpTrigger]
        Invoke url: https://myfunctionapp.azurewebsites.net/api/httptrigger?code=cCr8sAxfBiow548FBDLS1....

复制你的 HttpTrigger 的调用 URL 值,现在可以使用它在 Azure 中测试你的函数。Copy the Invoke URL value for your HttpTrigger, which you can now use to test your function in Azure. 该 URL 包含一个 code 查询字符串值,该值是你的函数密钥。The URL contains a code query string value that is your function key. 此密钥使得其他人难以在 Azure 中调用你的 HTTP 触发器终结点。This key makes it difficult for others to call your HTTP trigger endpoint in Azure.

在 Azure 中测试函数Test the function in Azure

使用 cURL 测试已部署的函数。Use cURL to test the deployed function. 使用从上一步复制的 URL,将查询字符串 &name=<yourname> 追加到该 URL,如以下示例所示:Using the URL that you copied from the previous step, append the query string &name=<yourname> to the URL, as in the following example:

curl https://myfunctionapp.azurewebsites.net/api/httptrigger?code=cCr8sAxfBiow548FBDLS1....&name=<yourname>

使用 cURL 在 Azure 中调用函数。

还可以将复制的 URL 粘贴到 Web 浏览器的地址中。You can also paste the copied URL in to the address of your web browser. 同样,在执行请求之前,先将查询字符串 &name=<yourname> 追加到该 URL。Again, append the query string &name=<yourname> to the URL before you execute the request.

使用 Web 浏览器调用函数。

后续步骤Next steps

已使用 HTTP 触发函数创建 Python 函数项目,在本地计算机上运行该项目,并将其部署到 Azure。You've created a Python functions project with an HTTP triggered function, run it on your local machine, and deployed it to Azure. 现在,通过以下方式扩展函数Now, extend your function by...