快速入門:從命令列在 Azure 中建立 Python 函式Quickstart: Create a Python function in Azure from the command line

在本文中,您會使用命令列工具建立可回應 HTTP 要求的 Python 函式。In this article, you use command-line tools to create a Python function that responds to HTTP requests. 在本機測試程式碼之後,您可以將其部署到 Azure Functions 的無伺服器環境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

完成本快速入門後,您的 Azure 帳戶中會產生幾美分或更少的少許費用。Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

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

設定您的本機環境Configure your local environment

開始之前,您必須具備下列條件:Before you begin, you must have the following:

先決條件檢查Prerequisite check

確認您的必要條件,這取決於您是使用 Azure CLI 還是 Azure PowerShell 來建立 Azure 資源:Verify your prerequisites, which depend on whether you are using Azure CLI or Azure PowerShell for creating Azure resources:

  • 在終端機或命令視窗中執行 func --version,以確認 Azure Functions Core Tools 為 3.x 版。In a terminal or command window, run func --version to check that the Azure Functions Core Tools are version 3.x.

  • 執行 az --version 以確認 Azure CLI 版本為 2.4 或更新版本。Run az --version to check that the Azure CLI version is 2.4 or later.

  • 執行 az login 以登入 Azure 並驗證有效訂用帳戶。Run az login to sign in to Azure and verify an active subscription.

  • 執行 python --version (Linux/macOS) 或 py --version (Windows),以確認您的 Python 版本回報為 3.8.x、3.7.x 或 3.6.x。Run python --version (Linux/macOS) or py --version (Windows) to check your Python version reports 3.8.x, 3.7.x or 3.6.x.

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

在適用的資料夾中執行下列命令,以建立並啟用名為 .venv 的虛擬環境。In a suitable folder, run the following commands to create and activate a virtual environment named .venv. 請務必使用受 Azure Functions 支援的 Python 3.8、3.7 或 3.6。Be sure to use Python 3.8, 3.7 or 3.6, which are supported by Azure Functions.

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

如果 Python 未在您的 Linux 發行版本上安裝 venv 套件,請執行下列命令:If Python didn't install the venv package on your Linux distribution, run the following command:

sudo apt-get install python3-venv

您將在這個已啟用的虛擬環境中執行所有後續命令。You run all subsequent commands in this activated virtual environment.

建立本機函式專案Create a local function project

在 Azure Functions 中,函式專案是包含一或多個個別函式的容器,而每個函式分別會回應特定的觸發程序。In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. 專案中的所有函式會共用相同的本機和裝載設定。All functions in a project share the same local and hosting configurations. 在本節中,您將建立包含單一函式的函式專案。In this section, you create a function project that contains a single function.

  1. 執行 func init 命令,以使用指定的執行階段在名為 LocalFunctionProj 的資料夾中建立函式專案:Run the func init command, as follows, to create a functions project in a folder named LocalFunctionProj with the specified runtime:

    func init LocalFunctionProj --python
    
  2. 瀏覽至專案資料夾:Navigate into the project folder:

    cd LocalFunctionProj
    

    此資料夾會包含專案的各種檔案,包括名為 local.settings.jsonhost.json 的組態檔。This folder contains various files for the project, including configurations files named local.settings.json and host.json. 由於 local.settings.json 可能會包含從 Azure 下載的秘密,因此 .gitignore 檔案依預設會將該檔案排除在原始檔控制以外。Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.

  3. 使用下列命令,將函式新增至您的專案,其中 --name 引數是函式的唯一名稱 (HttpExample),而 --template 引數可指定函式的觸發程序 (HTTP)。Add a function to your project by using the following command, where the --name argument is the unique name of your function (HttpExample) and the --template argument specifies the function's trigger (HTTP).

    func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"
    

    func new 會建立符合函式名稱的子資料夾,其中包含適合專案所選語言的程式碼檔案,以及名為 function.json 的組態檔。func new creates a subfolder matching the function name that contains a code file appropriate to the project's chosen language and a configuration file named function.json.

(選擇性) 檢查檔案內容(Optional) Examine the file contents

如有需要,您可以跳到在本機執行函式,並於稍後再檢查檔案內容。If desired, you can skip to Run the function locally and examine the file contents later.

__init__.py__init__.py

__init__.py 包含 main() Python 函式,此函式會根據 function.json 中的設定而觸發。__init__.py contains a main() Python function that's triggered according to the configuration in function.json.

import logging

import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

針對 HTTP 觸發程序,函式會接收變數 req 中的要求資料,如 function.json 中所定義。For an HTTP trigger, the function receives request data in the variable req as defined in function.json. reqazure.functions.HttpRequest 類別的執行個體。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.

function.jsonfunction.json

function.json 是一個組態檔,會定義函式的輸入和輸出 bindings,包括觸發程序類型。function.json is a configuration file that defines the input and output bindings for the function, including the trigger type.

如有需要,您可以變更 scriptFile 以叫用不同的 Python 檔案。You can change scriptFile to invoke a different Python file if desired.

{
    "scriptFile": "__init__.py",
    "bindings": [
        {
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "type": "http",
            "direction": "out",
            "name": "$return"
        }
    ]
}

每個繫結都需要方向、類型和唯一名稱。Each binding requires a direction, a type, and a unique name. HTTP 觸發程序具有 httpTrigger 類型的輸入繫結,和 http 類型的輸出繫結。The HTTP trigger has an input binding of type httpTrigger and output binding of type http.

在本機執行函式Run the function locally

  1. 啟動 LocalFunctionProj 資料夾中的本機 Azure Functions 執行階段主機,以執行您的函式:Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder:

    func start
    

    在輸出的結尾處,應該會出現下列幾行:Toward the end of the output, the following lines should appear:

     ...
    
     Now listening on: http://0.0.0.0:7071
     Application started. Press Ctrl+C to shut down.
    
     Http Functions:
    
             HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
     ...
    
     

    注意

    如果 HttpExample 未如下顯示,表示您可能不是從專案的根資料夾啟動主機。If HttpExample doesn't appear as shown below, you likely started the host from outside the root folder of the project. 在此情況下,請使用 Ctrl+C 停止主機,瀏覽至專案的根資料夾,然後再次執行先前的命令。In that case, use Ctrl+C to stop the host, navigate to the project's root folder, and run the previous command again.

  2. 從這個輸出中將 HttpExample 函式的 URL 複製到瀏覽器,並附加查詢字串 ?name=<YOUR_NAME>,使其成為完整的 URL (如 http://localhost:7071/api/HttpExample?name=Functions)。Copy the URL of your HttpExample function from this output to a browser and append the query string ?name=<YOUR_NAME>, making the full URL like http://localhost:7071/api/HttpExample?name=Functions. 瀏覽器應該會顯示類似於 Hello Functions 的訊息:The browser should display a message like Hello Functions:

    在本機瀏覽器中執行函式的結果

  3. 您在其中啟動專案的終端機,也會在您提出要求時顯示記錄輸出。The terminal in which you started your project also shows log output as you make requests.

  4. 完成作業後,請使用 Ctrl+C 並選擇 y 以停止函式主機。When you're done, use Ctrl+C and choose y to stop the functions host.

為您的函式建立支援的 Azure 資源Create supporting Azure resources for your function

若要將函式程式碼部署至 Azure,您必須先建立三個資源:Before you can deploy your function code to Azure, you need to create three resources:

  • 資源群組,這是相關資源的邏輯容器。A resource group, which is a logical container for related resources.
  • 儲存體帳戶,用來維護專案的狀態和其他資訊。A Storage account, which maintains state and other information about your projects.
  • 函式應用程式,可提供用來執行函式程式碼的環境。A function app, which provides the environment for executing your function code. 函式應用程式可對應至您的本機函式專案,並可讓您將函式分組為邏輯單位,以便管理、部署和共用資源。A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment, and sharing of resources.

請使用下列命令來建立這些項目。Use the following commands to create these items. Azure CLI 和 PowerShell 均受支援。Both Azure CLI and PowerShell are supported.

  1. 如果您尚未登入 Azure,請於此時登入:If you haven't done so already, sign in to Azure:

    az login
    

    az login 命令會將您登入您的 Azure 帳戶。The az login command signs you into your Azure account.

  2. westeurope 區域中,建立名為 AzureFunctionsQuickstart-rg 的資源群組。Create a resource group named AzureFunctionsQuickstart-rg in the westeurope region.

    az group create --name AzureFunctionsQuickstart-rg --location westeurope
    

    az group create 命令會建立資源群組。The az group create command creates a resource group. 您通常會使用 az account list-locations 命令傳回的可用區域,在您附近的區域中建立資源群組和資源。You generally create your resource group and resources in a region near you, using an available region returned from the az account list-locations command.

    注意

    您無法在相同的資源群組中裝載 Linux 和 Windows 應用程式。You can't host Linux and Windows apps in the same resource group. 如果您有名為 AzureFunctionsQuickstart-rg 的現有資源群組,且其中包含 Windows 函式應用程式或 Web 應用程式,則必須使用不同的資源群組。If you have an existing resource group named AzureFunctionsQuickstart-rg with a Windows function app or web app, you must use a different resource group.

  3. 在您的資源群組和區域中建立一般用途的儲存體帳戶:Create a general-purpose storage account in your resource group and region:

    az storage account create --name <STORAGE_NAME> --location westeurope --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS
    

    az storage account create 命令會建立儲存體帳戶。The az storage account create command creates the storage account.

    在上述範例中,請將 <STORAGE_NAME> 取代為適合您且在 Azure 儲存體中是唯一的名稱。In the previous example, replace <STORAGE_NAME> with a name that is appropriate to you and unique in Azure Storage. 名稱只能包含 3 到 24 個字元的數字和小寫字母。Names must contain three to 24 characters numbers and lowercase letters only. Standard_LRS 會指定受 Functions 支援的一般用途帳戶。Standard_LRS specifies a general-purpose account, which is supported by Functions.

    在本快速入門中,儲存體帳戶只會產生幾美分的費用。The storage account incurs only a few cents (USD) for this quickstart.

  4. 在 Azure 中建立函式應用程式:Create the function app in Azure:

    az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location westeurope --runtime python --runtime-version 3.8 --functions-version 3 --name <APP_NAME> --storage-account <STORAGE_NAME> --os-type linux
    

    az functionapp create 命令會在 Azure 中建立函式應用程式。The az functionapp create command creates the function app in Azure. 如果您使用 Python 3.7 或 3.6,請分別將 --runtime-version 變更為 3.73.6If you are using Python 3.7 or 3.6, change --runtime-version to 3.7 or 3.6, respectively.

    在上一個範例中,將 <STORAGE_NAME> 取代為您在上一個步驟中使用的帳戶名稱,並將 <APP_NAME> 取代為適合您的全域唯一名稱。In the previous example, replace <STORAGE_NAME> with the name of the account you used in the previous step, and replace <APP_NAME> with a globally unique name appropriate to you. <APP_NAME> 也是函式應用程式的預設 DNS 網域。The <APP_NAME> is also the default DNS domain for the function app.

    此命令會依據 Azure Functions 使用方案,建立在您指定的語言執行階段中執行的函式應用程式,而此應用程式在此處產生的使用量是免費的。This command creates a function app running in your specified language runtime under the Azure Functions Consumption Plan, which is free for the amount of usage you incur here. 此命令也會在相同的資源群組中佈建相關聯的 Azure Application Insights 執行個體,您可將其用於監視函式應用程式和檢視記錄。The command also provisions an associated Azure Application Insights instance in the same resource group, with which you can monitor your function app and view logs. 如需詳細資訊,請參閱監視 Azure FunctionsFor more information, see Monitor Azure Functions. 在您啟用此執行個體之前,並不會產生任何成本。The instance incurs no costs until you activate it.

將函式專案部署至 AzureDeploy the function project to Azure

在 Azure 中成功建立函式應用程式之後,您就可以開始使用 func Azure functionapp publish 命令部署本機函式專案。After you've successfully created your function app in Azure, you're now ready to deploy your local functions project by using the func azure functionapp publish command.

在下列範例中,請將 <APP_NAME> 取代為您的應用程式名稱。In the following example, replace <APP_NAME> with the name of your app.

func azure functionapp publish <APP_NAME>

發佈命令會顯示類似於下列輸出的結果 (為了簡單起見已將其截斷):The publish command shows results similar to the following output (truncated for simplicity):

...

Getting site publishing info...
Creating archive for current directory...
Performing remote build for functions project.

...

Deployment successful.
Remote build succeeded!
Syncing triggers...
Functions in msdocs-azurefunctions-qs:
    HttpExample - [httpTrigger]
        Invoke url: https://msdocs-azurefunctions-qs.azurewebsites.net/api/httpexample

在 Azure 上叫用函式Invoke the function on Azure

由於您的函式會使用 HTTP 觸發程序,因此您在叫用函式時,可以在瀏覽器中對其 URL 提出 HTTP 要求,或使用 curl 之類的工具。Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl.

將發佈命令的輸出中顯示的完整 叫用 URL 複製到瀏覽器網址列中 (請附加查詢參數 &name=Functions)。Copy the complete Invoke URL shown in the output of the publish command into a browser address bar, appending the query parameter &name=Functions. 瀏覽器應該會顯示與您在本機執行函式時類似的輸出。The browser should display similar output as when you ran the function locally.

使用瀏覽器在 Azure 上執行函式的輸出

執行下列命令,在 Azure 入口網站的 Application Insights 中檢視近乎即時的串流記錄Run the following command to view near real-time streaming logs in Application Insights in the Azure portal:

func azure functionapp logstream <APP_NAME> --browser

在個別終端機視窗或瀏覽器中,再次呼叫遠端函式。In a separate terminal window or in the browser, call the remote function again. Azure 中的函式執行會有詳細資訊記錄顯示在終端機中。A verbose log of the function execution in Azure is shown in the terminal.

清除資源Clean up resources

如果您要繼續進行下一個步驟並新增 Azure 儲存體佇列輸出繫結,請保留您所有的資源,因為在後續的工作還會用到。If you continue to the next step and add an Azure Storage queue output binding, keep all your resources in place as you'll build on what you've already done.

否則,請使用下列命令刪除資源群組及其包含的所有資源,以避免產生額外的成本。Otherwise, use the following command to delete the resource group and all its contained resources to avoid incurring further costs.

az group delete --name AzureFunctionsQuickstart-rg

後續步驟Next steps

有任何問題嗎?請告訴我們。Having issues? Let us know.