快速入門:在 Azure 中建立 HTTP 觸發的 Python 函式Quickstart: Create an HTTP triggered Python 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 要求所觸發的函式。You also create a function that is triggered by an HTTP request. 在本機執行之後,您會在 Azure 中發行專案,使其以無伺服器函式的形式執行。After running locally, you publish your project to run as a serverless function in Azure.

本文是 Azure Functions 的兩個 Python 快速入門中的第一個。This article is the first of two Python quickstarts for Azure Functions. 當您完成本快速入門後,您可以將 Azure 儲存體佇列輸出繫結新增至您的函式。After you complete this quickstart, you can add an Azure Storage queue output binding to your function.

這也是本文的 Visual Studio Code 版本There is also a Visual Studio Code-based version of this article.

必要條件Prerequisites

開始之前,您必須:Before you start, you must:

建立並啟用虛擬環境Create and activate a virtual environment

您應使用 Python 3.7 環境,在本機開發 Python 功能。You should use a Python 3.7 environment to locally develop Python functions. 執行下列命令來建立並啟用名為 .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:

python -m venv .venv
source .venv/bin/activate

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

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

您現在已啟用虛擬環境,請在其中執行其餘的命令。Now that you activated the virtual environment, run the remaining commands in it. 若要離開虛擬環境,請執行 deactivateTo get out of the virtual environment, run deactivate.

建立本機 Functions 專案Create a local functions project

Functions 專案可以有多個全都共用相同本機和裝載設定的函式。A functions project can have multiple functions that all share the same local and hosting configurations.

在虛擬環境中,執行下列命令:In the virtual environment, run the following commands:

func init MyFunctionProj --python
cd MyFunctionProj

func init 命令會建立 MyFunctionProj 資料夾。The func init command creates a MyFunctionProj folder. 此資料夾中的 Python 專案還沒有任何函式。The Python project in this folder doesn't yet have any functions. 接下來,您將加入函式。You'll add them next.

建立函式Create a function

若要將函式新增至專案,請執行下列命令:To add a function to your project, run the following command:

func new --name HttpTrigger --template "HTTP trigger"

此命令會建立名為 HttpTrigger 的子資料夾,其中包含下列檔案:This commands creates a subfolder named HttpTrigger, which contains the following files:

  • function.json:定義函式、觸發程序和其他繫結的組態檔。function.json: configuration file that defines the function, trigger, and other bindings. 請注意在此檔案中,scriptFile 的值會指向包含此函式的檔案,而 bindings 陣列會定義引動過程觸發程序和繫結。Notice that in this file, the value for scriptFile points to the file containing the function, and the bindings array defines the invocation trigger and bindings.

    每個繫結都需要方向、類型和唯一名稱。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() 值。Notice that this script has a default main(). 來自觸發程序的 HTTP 資料會使用名為 binding parameterreq 傳遞至函數。HTTP data from the trigger passes to the function using the req named binding parameter. req (定義於 function.json 中) 是 azure.functions.HttpRequest 類別的執行個體。The req, which is defined in function.json, 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.

現在您可以在本機電腦上執行新的函式。Now you can run the new function on your local computer.

在本機執行函式Run the function locally

此命令會使用 Azure Functions 執行階段 (func.exe) 啟動函式應用程式:This command starts the function app using the Azure Functions runtime (func.exe):

func host start

您應該會看到寫入輸出的下列資訊:You should see the following information written to the output:

Http Functions:

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

從此輸出複製 HttpTrigger 函式的 URL,並將它貼到瀏覽器的網址列。Copy the URL of your HttpTrigger function from this 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 screenshot shows the response to the GET request that the local function returns to the browser:

在瀏覽器中進行本機驗證

使用 Ctrl+C 關閉您的函式應用程式執行。Use Ctrl+C to shut down your function app execution.

現在您已在本機執行函式,接下來您可以將函式程式碼部署至 Azure。Now that you have run your function locally, you can deploy your function code to Azure.
在部署應用程式之前,您必須先建立一些 Azure 資源。Before you can deploy your app, you'll need to create some Azure resources.

建立資源群組Create a resource group

使用 az group create 命令來建立資源群組。Create a resource group with the az group create command. 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 aren't 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.

執行下列命令。Run the following command. 使用唯一的函式應用程式名稱取代 <APP_NAME>Replace <APP_NAME> with a unique function app name. 使用儲存體帳戶名稱取代 <STORAGE_NAME>Replace <STORAGE_NAME> with a storage account 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.

注意

您無法在相同的資源群組中裝載 Linux 和 Windows 應用程式。You can't host Linux and Windows apps 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.

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

上述命令會建立執行 Python 3.7.4 的函式應用程式。The preceding command creates a function app running Python 3.7.4. 該命令也會在相同的資源群組中佈建相關聯的 Azure Application Insights 執行個體。It also provisions an associated Azure Application Insights instance in the same resource group. 您可以使用此執行個體來監視函式應用程式及檢視記錄。You can use this instance to monitor your function app and view 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 Tools 命令將專案程式碼部署至 Azure。After you create the function app in Azure, you can use the func azure functionapp publish Core Tools command to deploy your project code to Azure. 在此範例中,使用您的應用程式名稱取代 <APP_NAME>In this example, replace <APP_NAME> with the name of your app.

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, which is recommended.

您會看到類似於下列訊息的輸出。You'll see output similar to the following message. 輸出會在此截斷,以便更清楚地閱讀:It's truncated here so you can read it better:

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....

您可以複製您的 HttpTriggerInvoke url 值,並使用它在 Azure 中驗證您的函式。You can copy the Invoke url value for your HttpTrigger and use it to verify your function in Azure. URL 包含 code 查詢字串值,這是您的函式金鑰,可讓其他人難以在 Azure 中呼叫您的 HTTP 觸發程式端點。The URL contains a code query string value that is your function key, which makes it difficult for others to call your HTTP trigger endpoint in Azure.

驗證 Azure 中的函式Verify the function in Azure

使用 cURL 來驗證已部署的函式。Use cURL to verify 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, into the address bar 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, use 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...