在 Azure 中建立 HTTP 觸發的函式Create an HTTP triggered function in Azure

本文說明如何使用命令列工具建立在 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.

必要條件Prerequisites

開始之前,您必須符合下列條件: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 (optional)

若要在本機開發及測試 Python 函式,建議您使用 Python 3.6 環境。To locally develop and test Python functions, it is recommended to use a Python 3.6 environment. 執行下列命令來建立並啟用名為 .venv 的虛擬環境。Run the following commands to create and activate a virtual environment named .venv.

注意

如果 Python 未在您的 Linux 發行版本上安裝 venv,您可以使用下列命令來安裝它:If Python didn't install venv on your Linux distribution, you can install it using the following command:

sudo apt-get install python3-venv

Bash:Bash:

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

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

py -3.6 -m venv .venv
.venv\scripts\activate

其餘命令會在虛擬環境中執行。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

建立函式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. req 定義於 function.json 中,是 azure.functions.HttpRequest 類別的執行個體。Defined in function.json, req is an instance of the azure.functions.HttpRequest class.

    傳回物件在 function.json 中定義為 $return,是 azure.functions.HttpResponse 類別的執行個體。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: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.

...

Http Functions:

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

[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.
如果您未使用 Cloud 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.

建立 Azure 儲存體帳戶Create an Azure Storage account

函式會使用 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 中建立函式應用程式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>

注意

Linux 和 Windows 應用程式無法裝載在相同的資源群組中。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 Application Insights 執行個體。This command will also provision an associated Azure Application Insights instance in the same resource group that can be used for monitoring and viewing logs.

您現在已準備好將本機 Functions 專案發佈至 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 工具命令來將專案程式碼部署至 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 these examples, replace <APP_NAME> with the name of your app from the previous step.

func azure functionapp publish <APP_NAME> --build remote

--build remote 選項會透過部署套件中的檔案,從遠端在 Azure 中建立 Python 專案。The --build remote option builds your Python project remotely in Azure from the files in the deployment package.

您會看到類似下列的輸出,該輸出已截短,以提高可讀性:You'll 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 的叫用 Invoke 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, including the function key, that you copied from the previous step, append the query string &name=<yourname> to the URL.

使用 cURL 來呼叫 Azure 中的函式。

您也可以將複製的 URL (包括函式索引鍵) 貼至網頁瀏覽器的位址。You can also paste the copied URL, including the function key, 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.

使用網頁瀏覽器來呼叫函式。

注意

若要針對已發佈的 Python 應用程式檢視近乎即時的記錄,建議您使用 Application Insights 即時計量資料流To view near real-time logs for a published Python app, we recommend using the Application Insights Live Metrics Stream

後續步驟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...