Azure 函數開發者參考指南:適用於 Python 應用程式

Azure Functions 是一個無伺服器運算服務,讓你能在不需配置或管理基礎設施的情況下執行事件驅動的程式碼。 函式執行會由 HTTP 請求、佇列訊息、計時器或儲存變更等事件觸發,並根據需求自動擴展。

本指南專注於建立基於 Python 的 Azure Functions,並幫助你:

  • 本地建立並執行函式應用程式
  • 了解 Python 程式設計模型
  • 組織與配置您的應用程式
  • 在 Azure 部署並監控你的應用程式
  • 應用提升擴充性與效能的最佳做法

想要一個概念性的概述嗎? 請參閱 Azure Functions 開發者參考。

對實際應用場景感興趣嗎? 探索「 情境與範例 」頁面。

入門指南

選擇適合你工作流程的環境,然後直接進入 Azure Functions for Python:

建立您的函式應用程式

本節涵蓋建立與結構化 Python 函式應用程式所需的基本元件。 主題包括 程式設計模型、 專案結構、 觸發器與綁定,以及 相依性管理。

程式設計模型

函式支援兩個版本的 Python 程式設計模型:

版本 描述
2.x 使用裝飾器式的方法,直接在你的 Python 程式碼檔案中定義觸發器和綁定。 你將每個函式實作為全域且無狀態的方法,存放在 function_app.py 檔案或參考藍圖檔案中。 此模型版本建議用於新開發的 Python 應用程式。
1.x 你可以在獨立 function.json 的檔案中為每個函式定義觸發器和綁定。 你在 Python 程式碼檔中實作每個函式,作為全域、無狀態的方法。 此版本的模型支援舊有應用程式。

本文針對特定 Python 模型版本。 請在 文章頂部選擇你想要的版本。

重要事項

使用 v2 程式模型,採用 裝飾器為基礎的方法 ,直接在程式碼中定義觸發器和綁定。

在 Python v1 程式設計模型中,每個函式定義為全域無狀態的 main() 方法,置於名為 __init__.py 的檔案中。 函式的觸發器和綁定分別在function.json檔案中設定,綁定name值用作你main()方法中的參數。

範例

這裡有一個簡單的函式,可以回應 HTTP 請求:

# __init__.py
def main(req):
    user = req.params.get('user')
    return f'Hello, {user}!'

這是對應 function.json 的檔案:

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

重要概念

  • 這個函式只有一個 HTTP 觸發器。
  • HttpRequest 物件包含請求標頭、查詢參數、路由參數及訊息主體。 此函式會從 nameparams 物件的參數取得查詢參數的值。
  • 在此範例中,要傳送名稱,請將 ?name={name} 附加到公開的函式 URL。 例如,若在本地執行,完整網址可能看起來像 http://localhost:7071/api/http_trigger?name=Test。 關於使用綁定的範例,請參見 觸發器與綁定。

使用 azure-functions SDK 並加入 型別註解 ,以提升 IntelliSense 與編輯器的支援:

# __init__.py
import azure.functions as func

def http_trigger(req: func.HttpRequest) -> str:
# requirements.txt
azure-functions

azure-functions圖書館

azure-functions Python 函式庫提供用於與 Azure Functions 執行時互動的核心型別。 欲查看所有可用類型與方法,請造訪 azure-functions API。 你的函式程式碼可以用 azure-functions 來:

  • 存取觸發輸入資料(例如, HttpRequest, TimerRequest)
  • 建立輸出值(例如 HttpResponse)
  • 與執行時提供的上下文與綁定資料互動

如果你在應用程式中使用 azure-functions ,請將它納入專案相依關係中。

附註

azure-functions 函式庫定義了 Python Azure Functions 的程式介面,但它不是通用的 SDK。 專門用它來撰寫和執行 Azure Functions 執行時的函式。

替代進入點

你可以透過在檔案中指定 scriptFile 和 entryPoint 屬性 function.json 來改變函式的預設行為。 例如,以下的 function.json 檔案指示執行時使用 custom_entry() 檔案中的 main.py 方法作為 Azure 函式的入口。

{
  "scriptFile": "main.py",
  "entryPoint": "custom_entry",
  "bindings": [
      ...
  ]
}

資料夾結構

Python Azure Functions專案請採用以下結構:

<project_root>/
│
├── .venv/                   # (Optional) Local Python virtual environment
├── .vscode/                 # (Optional) VS Code workspace settings
│
├── my_first_function/       # Function directory
│   └── __init__.py          # Function code file
│   └── function.json        # Function binding configuration file
│
├── my_second_function/
│   └── __init__.py  
│   └── function.json 
│
├── shared/                  # (Optional) Pure helper code with no triggers/bindings
│   └── utils.py
│
├── additional_functions/    # (Optional) Contains blueprints for organizing related Functions
│   └── blueprint_1.py  
│
├── tests/                   # (Optional) Unit tests for your functions
│   └── test_my_function.py
│
├── .funcignore              # Excludes files from being published
├── host.json                # Global function app configuration
├── local.settings.json      # Local-only app settings (not published)
├── requirements.txt         # (Optional) Defines Python dependencies for remote build
├── Dockerfile               # (Optional) For custom container deployment

金鑰檔案與資料夾

檔案/資料夾 描述 在 Azure 中運行應用程式所需
my_first_function/ 單一函式的目錄。 ✅
__init__.py/ 主腳本,定義 my_first_function 函式程式碼。 ✅
function.json/ 包含 my_first_function 函式的繫結組態。 ✅
host.json 應用程式中所有功能的全域配置。 ✅
requirements.txt 在使用remote build進行發佈時安裝的Python依賴。 ❌ (建議用於套件管理)
local.settings.json 僅限本地應用程式設定與秘密(從未公開)。 ❌ (地方發展所需)
.funcignore 指定要排除部署的檔案和資料夾(例如, .venv/, tests/, local.settings.json)。 ❌ (建議)
.venv/ Python 的本地虛擬環境(不包含部署)。 ❌
.vscode/ Visual Studio Code 的編輯器設定。 部署時不需要。 ❌
shared/ 儲存 Function App 專案中共享的輔助程式碼 ❌
additional_functions/ 用於模組化程式碼組織——通常搭配 藍圖。 ❌
tests/ 功能應用程式的單元測試。 未發佈到 Azure。 ❌
Dockerfile 定義一個自訂的部署容器。 ❌

在 Python v2 程式設計模型中,Azure Functions 採用裝飾器的方法,直接在程式碼中定義觸發器和綁定。 每個函式都以 全域、無狀態的方法 實作於檔案中 function_app.py 。

範例

這裡有一個簡單的函式,可以回應 HTTP 請求:

import azure.functions as func

app = func.FunctionApp()

@app.route("hello")
def http_trigger(req):
    user = req.params.get("user")
    return f"Hello, {user}!"
# requirements.txt
azure-functions

重要概念

  • 程式碼引入azure-functions套件,並使用裝飾器和類型來定義函式 app。
  • 這個函式只有一個 HTTP 觸發器。
  • HttpRequest 物件包含請求標頭、查詢參數、路由參數及訊息主體。 此函式會從 nameparams 物件的參數取得查詢參數的值。
  • 在此範例中,要傳送名稱,請將 ?name={name} 附加到公開的函式 URL。 例如,若在本地執行,完整網址可能看起來像 http://localhost:7071/api/http_trigger?name=Test。 關於使用綁定的範例,請參見 觸發器與綁定。

azure-functions圖書館

azure-functions Python 函式庫是 Azure Functions 程式設計模型的核心部分。 它提供裝飾器、觸發器與綁定型別,以及用於定義及執行時與函式互動的請求/回應物件。 想查看所有類型和裝飾項目,請造訪 azure-functions API。 你的函式應用程式程式碼依賴這個函式庫來:

  • 使用 FunctionApp 物件定義所有函數
  • 宣告觸發條件與綁定(例如, @app.route, @app.timer_trigger)
  • 存取具類型輸入和輸出 (例如 HttpRequest 和 HttpResponse,以及 Out`)

你必須將 azure-functions 加入專案相依性中。 欲了解更多,請參閱 套件管理。

附註

azure-functions 函式庫定義了 Python Azure Functions 的程式介面,但它不是通用的 SDK。 專門用它來撰寫和執行 Azure Functions 執行時的函式。

使用 類型註解 來提升 IntelliSense 與編輯器的支援:

def http_trigger(req: func.HttpRequest) -> str:

讀取路由參數

你可以直接在 HTTP 路由範本中定義路由參數,並從請求物件讀取。

例如,路由 products/{product_id} 會從 URL 路徑擷取該值,並透過 HttpRequest.route_params提供。

import azure.functions as func

app = func.FunctionApp()

@app.route(route="products/{product_id}", methods=["GET"])
def get_product(req: func.HttpRequest) -> func.HttpResponse:
    product_id = req.route_params.get("product_id")
    if not product_id:
        return func.HttpResponse("Missing route parameter: product_id", status_code=400)
    return func.HttpResponse(f"Product: {product_id}")

重要事項

在 Python v2 模型中,不要把路由參數當作額外的函式參數。 請改為從req.route_params讀取。

用藍圖組織

對於較大或模組化的應用程式,可以使用 blueprints 在獨立的 Python 檔案中定義功能,並註冊到你的主應用程式。 這種分離方式能讓你的程式碼保持有條理且可重複使用。

要定義並註冊藍圖:

  1. 在另一個Python檔案中定義藍圖,例如 http_blueprint.py:

    import azure.functions as func
    
    bp = func.Blueprint()
    
    @bp.route(route="default_template")
    def default_template(req: func.HttpRequest) -> func.HttpResponse:
        return func.HttpResponse("Hello World!")
    
  2. 在主 function_app.py 檔案中註冊藍圖:

    import azure.functions as func
    from http_blueprint import bp
    
    app = func.FunctionApp()
    app.register_functions(bp)
    

透過使用藍圖,你可以:

  • 將應用程式拆分成可重複使用的模組
  • 將相關函數依檔案或功能分組
  • 跨專案延伸或分享藍圖

附註

Durable Functions也支援使用 azure-functions-durable 來製作藍圖。 查看範例 →

資料夾結構

Python Azure Functions專案請採用以下結構:

<project_root>/
│
├── .venv/                   # (Optional) Local Python virtual environment
├── .vscode/                 # (Optional) VS Code workspace settings
│
├── function_app.py          # Main function entry point (decorator model)
├── shared/                  # (Optional) Pure helper code with no triggers/bindings
│   └── utils.py
│
├── additional_functions/    # (Optional) Contains blueprints for organizing related Functions
│   └── blueprint_1.py  
│
├── tests/                   # (Optional) Unit tests for your functions
│   └── test_my_function.py
│
├── .funcignore              # Excludes files from being published
├── host.json                # Global function app configuration
├── local.settings.json      # Local-only app settings (not published)
├── requirements.txt         # (Optional) Defines Python dependencies for remote build
├── Dockerfile               # (Optional) For custom container deployment

金鑰檔案與資料夾

檔案/資料夾 描述 在 Azure 中運行應用程式所需
function_app.py 使用裝飾項目定義 Azure Functions 與觸發程序的主要指令碼。 ✅
host.json 應用程式中所有功能的全域配置。 ✅
requirements.txt 在使用remote build進行發佈時安裝的Python依賴。 ❌ (建議用於套件管理)
local.settings.json 僅限本地應用程式設定與秘密(從未公開)。 ❌ (地方發展所需)
.funcignore 指定要排除部署的檔案和資料夾(例如, .venv/, tests/, local.settings.json)。 ❌ (建議)
.venv/ Python 的本地虛擬環境(不包含部署)。 ❌
.vscode/ Visual Studio Code 的編輯器設定。 部署時不需要。 ❌
shared/ 儲存 Function App 專案中共享的輔助程式碼 ❌
additional_functions/ 用於模組化程式碼組織——通常搭配 藍圖。 ❌
tests/ 功能應用程式的單元測試。 未發佈到 Azure。 ❌
Dockerfile 定義一個自訂的部署容器。 ❌

附註

部署時用requirements.txt時,記得附上檔案。 如果你不使用遠端建置,或想用其他檔案來定義應用程式相依,你可以執行 本地編譯 ,並用預建的相依部署應用程式。

欲了解更多資訊,請參閱:


觸發和繫結

Azure Functions 使用 triggers來啟動函式執行,並使用 bindings 來連接你的程式碼到其他服務,如儲存、佇列和資料庫。 在 Python v2 程式設計模型中,您是透過使用裝飾器來宣告綁定。

綁定主要有兩種類型:

  • 觸發器 (啟動函式的輸入)
  • 輸入與輸出 (額外資料來源或目的地)

欲了解更多可用的觸發條件與綁定資訊,請參閱Azure Functions 中的觸發條件與綁定。

範例:帶有 Blob 輸入的計時器觸發

此功能:

  • 每10分鐘觸發一次
  • 使用 SDK 型別綁定來從 Blob 進行讀取
  • 快取結果並寫入暫存檔案
import azure.functions as func
import azurefunctions.extensions.bindings.blob as blob
import logging
import tempfile

CACHED_BLOB_DATA = None

app = func.FunctionApp()

@app.function_name(name="TimerTriggerWithBlob")
@app.schedule(schedule="0 */10 * * * *", arg_name="mytimer")
@app.blob_input(arg_name="client",
                path="PATH/TO/BLOB",
                connection="BLOB_CONNECTION_SETTING")
def timer_trigger_with_blob(mytimer: func.TimerRequest,
                            client: blob.BlobClient,
                            context: func.Context) -> None:
    global CACHED_BLOB_DATA
    if CACHED_BLOB_DATA is None:
        # Download blob and save as a global variable
        CACHED_BLOB_DATA = client.download_blob().readall()

        # Create temp file prefix
        my_prefix = context.invocation_id
        temp_file = tempfile.NamedTemporaryFile(prefix=my_prefix)
        temp_file.write(CACHED_BLOB_DATA)
        logging.info(f"Cached data written to {temp_file.name}")

重要概念

  • 使用 SDK 類型綁定來處理豐富類型。 欲了解更多資訊,請參閱 SDK 類型綁定。
  • 你可以用全域變數來快取昂貴的運算,但它們的狀態無法保證在函式執行中持續存在。
  • 暫存檔案會儲存在 tmp/ 中,於不同呼叫或擴展實例間不保證能持續存在。
  • 你可以透過 Context 類別存取函式的調用上下文。

範例:HTTP 觸發器搭配 Cosmos DB 輸入與事件中心輸出

此功能:

  • HTTP 請求的觸發器
  • 從 Cosmos DB 的讀取
  • 寫入至 Event Hub 的輸出
  • 回傳 HTTP 回應
# __init__.py
import azure.functions as func

def main(req: func.HttpRequest,
         documents: func.DocumentList,
         event: func.Out[str]) -> func.HttpResponse:

    # Content from HttpRequest and Cosmos DB input
    http_content = req.params.get("body")
    doc_id = documents[0]["id"] if documents else "No documents found"

    event.set(f"HttpRequest content: {http_content} | CosmosDB ID: {doc_id}")

    return func.HttpResponse(
        "Function executed successfully.",
        status_code=200
    )
// function.json
{
  "scriptFile": "__init__.py",
  "entryPoint": "main",
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["get", "post"],
      "route": "file"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "type": "cosmosDB",
      "direction": "in",
      "name": "documents",
      "databaseName": "test",
      "containerName": "items",
      "id": "cosmosdb-input-test",
      "connection": "COSMOSDB_CONNECTION_SETTING"
    },
    {
      "type": "eventHub",
      "direction": "out",
      "name": "event",
      "eventHubName": "my-test-eventhub",
      "connection": "EVENTHUB_CONNECTION_SETTING"
    }
  ]
}

關鍵概念

  • 每個函式只有一個觸發器,但可以有多個綁定。
  • 要加入輸入,請在direction中將function.json指定為「in」。 輸出具有 direction,其值為 out。
  • 你可以透過 HttpRequest 物件存取請求細節,並建立包含標頭、狀態碼和正文的自訂 HttpResponse 檔案。
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="HttpTriggerWithCosmosDB")
@app.route(route="file")
@app.cosmos_db_input(arg_name="documents",
                     database_name="test",
                     container_name="items",
                     connection="COSMOSDB_CONNECTION_SETTING")
@app.event_hub_output(arg_name="event",
                      event_hub_name="my-test-eventhub",
                      connection="EVENTHUB_CONNECTION_SETTING")
def http_trigger_with_cosmosdb(req: func.HttpRequest,
                               documents: func.DocumentList,
                               event: func.Out[str]) -> func.HttpResponse:
    # Content from HttpRequest and Cosmos DB input
    http_content = req.params.get('body')
    doc_id = documents[0]['id']

    event.set("HttpRequest content: " + http_content
              + " | CosmosDB ID: " + doc_id)

    return func.HttpResponse(
        f"Function executed successfully.",
        status_code=200
    )

重要概念

  • 使用 @route() 或針對特定觸發器的裝飾工具(@timer_trigger、 @queue_trigger及其他)來定義你的功能如何被調用。
  • 使用像 @blob_input、 @queue_input、 等裝飾工具來添加輸入。
  • 輸出可以是:
    • 直接回傳(如果只有一個輸出)
    • 使用 Out 繫結和 .set() 方法來指派多個輸出。
  • 你可以透過 HttpRequest 物件存取請求細節,並建立包含標頭、狀態碼和正文的自訂 HttpResponse 檔案。

SDK 類型系結

針對特定觸發程序與繫結,您可以使用基礎 Azure SDK 與架構實作的資料型別。 透過使用這些 SDK 類型的綁定,你可以像使用底層服務 SDK 一樣與綁定資料互動。 欲了解更多資訊,請參閱 支援的 SDK 類型綁定。

重要事項

Python 的 SDK 類型綁定支援僅在 Python v2 程式模型中提供。

藥劑結合

重要事項

Python 函式應用程式的代理綁定目前處於預覽階段。 功能、套件名稱及設定在正式推出前可能會變更。

代理綁定讓你能在保留標準 Azure Functions 觸發器、綁定和應用邏輯的同時,將代理物件注入函式。 你可以使用 Agent 繫結,將確定性程式碼與代理式推理結合,包括在 Durable Functions 協調流程中。 欲了解更多資訊,請參閱 Python 函式應用程式的代理綁定。

環境變數

Azure Functions 中的環境變數讓你能安全地管理設定值、連線字串和應用程式秘密,而不必將它們硬編碼在函式程式碼中。

你可以定義環境變數:

可直接在程式碼中存取變數,使用 os.environ 或 os.getenv。

setting_value = os.getenv("myAppSetting", "default_value")

附註

Azure Functions 也識別系統環境變數,這些變數用來配置 Functions 執行時和 Python 工作者行為。 這些變數不會明確用於你的函式程式碼,但會影響應用程式的執行方式。 完整系統環境變數清單,請參閱應用程式設定參考。

套件管理

要在你的 Azure Functions app 中使用其他 Python 套件,請在專案根目錄的 requirements.txt 檔案中列出它們。 Python 的匯入系統會匯入這些套件,你可以照常參考它們。 欲了解更多關於有外部相依性的建置與部署選項,請參閱 Python Function Apps 的建置選項。

例如,以下範例展示了該模組如何在 requests 函式應用程式中被包含與使用。

<requirements.txt>
requests==2.31.0

用 pip install -r requirements.txt 在本地安裝套件。

安裝套件後,你可以匯入並在函式程式碼中使用:

import azure.functions as func
import requests

def main(req: func.HttpRequest) -> func.HttpResponse:
    r = requests.get("https://api.github.com")
    return func.HttpResponse(f"Status: {r.status_code}")
import azure.functions as func
import requests

app = func.FunctionApp()

@app.function_name(name="HttpExample")
@app.route(route="call_api")
def main(req: func.HttpRequest) -> func.HttpResponse:
    r = requests.get("https://api.github.com")
    return func.HttpResponse(f"Status: {r.status_code}")

考慮事項

  • 與內建模組的衝突:
    • 避免用Python標準函式庫來命名專案資料夾(例如email/、json/)。
    • 不要在 logging 中包含Python原生函式庫(例如 asyncio、uuid 或 requirements.txt)。
  • 部署:
    • 為避免 ModuleNotFound 錯誤,請確保你在 requirements.txt 中列出所有必要的相依關係。
    • 如果你更新了應用程式的 Python 版本,請在新的 Python 版本上重建並重新部署應用程式,以避免與先前建立的套件產生相依性衝突。
  • 非 PyPI 相依:
  • Azure Functions Python 工作者依賴關係:
    • 如果你的套件包含某些函式庫可能會與工作者的相依性發生衝突(例如, protobuf 或 grpcio),請將 PYTHON_ISOLATE_WORKER_DEPENDENCIES 設為 1 應用程式內設定,以防止應用程式引用工作者的相依性。 在 Python 3.13 及更新版本中,此功能預設啟用。

執行與部署

本節提供有關 本地運行函式、Python 版本支援、建置與部署選項,以及執行時設定的資訊。 利用這些資訊,成功在本地和 Azure 環境中執行你的函式應用程式。

正在本機執行

你可以在本地機器上執行並測試你的 Python 函式應用程式,再部署到 Azure。

使用 Azure Functions Core 工具

安裝 Azure Functions Core Tools,並從專案根執行 func start 指令啟動本地執行環境:

func start

當你在本地啟動函式應用程式時,Core Tools 會顯示它為你的應用程式找到的所有函式:

Functions:
        http_trigger:  http://localhost:7071/api/http_trigger

你可以造訪 使用 Core Tools 在本地開發 Azure Functions 來了解如何使用 Core Tools。

直接調用函數

使用 azure-functions >= 1.21.0,你也可以直接使用 Python 直譯器呼叫函式,無需執行 Core Tools。 此方法適用於快速單元測試:

# function_app.py
import azure.functions as func

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    return "Hello, World!"

# Test the function directly
print(http_trigger(None))

要查看輸出,請直接用 Python 執行該檔案:

> python function_app.py

Hello, World!
# __init__.py
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    return func.HttpResponse("Hello, World!")

# Test the function directly
print(main(None))

要查看輸出,請直接用 Python 執行該檔案:

> python __init__.py

Hello, World!

這種方法不需要額外的套件或設定,非常適合開發過程中快速驗證。 欲了解更多深入測試,請參見 單元測試。

支援的 Python 版本

Azure Functions 支援Azure Functions 支援的語言中列出的 Python 版本。 欲了解更多一般資訊,請參閱 Azure Functions 執行時支援政策。

更新應用程式時請考慮以下事項:

  • 如果現有的 Python 3.11 應用程式在 Linux 彈性高級版或專用版(App Service)方案中使用 Debian Bullseye 管理映像檔,請將該應用程式更新為 Debian Bookworm 映像檔,以維持在支援的 Linux 發行版上。
  • 如果您變更函式應用程式的 Python 版本,請使用新版本重新建置應用程式及其相依性。
  • 重新部署重建的應用程式。 更改 Python 版本並不會自動重建現有的部署產物和依賴。

建置和部署

想了解更多建議的建造機制,請參閱 建構選項。 關於部署的一般概述,請參見Azure Functions 中的部署技術。

部署機制快速比較

工具 / 平台 指揮/行動 最佳使用案例
Azure Functions 核心工具 func azure functionapp publish <APP_NAME> 非常適合 CI 執行、本地自動化,或跨平台作業時使用。
AZ CLI az functionapp deployment source config-zip 在執行 Core Tools 以外的部署腳本時非常有用。 它在自動化管線或雲端終端機(Azure Cloud Shell)中運作良好。
Visual Studio Code(適用於 Azure Functions 的擴充功能) 指令調色盤→「Azure Functions:部署到Azure......」 最適合初學者或互動式部署。 自動處理包裝與組裝。
GitHub Actions Azure/functions-action@v1 非常適合基於 GitHub 的 CI/CD。 啟用推送或 PR 合併時的自動化部署。
Azure Pipelines AzureFunctionApp@2 任務 使用 Azure DevOps 的企業 CI/CD。 最適合受控釋出工作流程、閘控建置和多階段管線。
自訂容器部署 推送容器 → az functionapp create --image <container> 當你需要作業系統層級的套件、自訂的 Python 編譯、固定的執行階段環境,或不支援的相依項(例如系統函式庫、本地二進位檔)時,這是必要的。
入口網站功能建立 在 Azure portal → 內嵌編輯器中建立函式 僅用於 簡單且無依賴的函式。 非常適合示範或學習,但 不建議 用於需要第三方套件的應用程式。

附註

基於入口網站的功能創建 不支援第三方相依,也不建議用於生產應用程式的開發。 你無法安裝或參考任何套件,除了 azure-functions 和內建的 Python 標準函式庫。

重要事項

在 Linux 上使用 Consumption 計劃且仍使用已到期的 v3 執行階段 的函式應用程式,在 2026 年 9 月 30 日後將停止運行。 為避免服務中斷,請將 應用程式遷移到 v4 執行環境。

在 Linux 上以 Consumption 方案託管功能應用程式的選項將於 2028 年 9 月 30 日終止。 Linux 消費方案沒有新增功能或 語言版本。 在 Windows 上運行的 Consumption 方案應用程式目前不受影響。 在退休日前將應用程式遷移到 Flex Consumption 計畫。

Python 3.13+ 更新

從 Python 3.13 開始,Azure Functions 引入了多項重大的執行時與效能改進,影響你建置與執行應用程式的方式。 主要變化包括:

  • 執行時版本控制:你現在可以選擇性地將應用程式釘選或升級到特定的 Python 工作者版本,方法是參考你的 azure-functions-runtime 中的 requirements.txt 套件。

    • 若不啟用版本控制,您的應用程式會運行在預設版本的 Python 執行時,而 Functions 會管理該執行環境。 您必須修改您的 requirements.txt 檔案,以請求最新發布版本、預發布版本,或將應用程式固定到特定版本的 Python 執行環境。

    • 您可以透過在 requirements.txt 檔案中加入對 Python 執行時套件的引用來啟用執行時版本控制,其中為該套件指派的值決定使用的執行時版本。

    • 避免將生產應用程式綁定到測試版(alpha、beta 或開發版)的執行時版本。

    • 要了解變更,請定期檢視 Python 執行時發布說明。

    • 下表顯示根據您 requirements.txt 檔案中此設定的版本值所進行的版本管理行為:

      版本 範例 行為
      沒有值設定 azure-functions-runtime 你的 Python 3.13+ 應用程式運行於最新版本的 Functions Python 執行環境上。 這個選項最適合隨時掌握平台改進與功能,因為你的應用程式會自動收到最新的穩定執行時更新。
      已固定至特定版本 azure-functions-runtime==1.2.0 你的 Python 3.13+ 應用程式會保持在固定的執行時間版本,且不會自動更新。 您必須手動更新釘選的版本,才能使用執行階段的新功能、修正與改進。 釘定建議用於關鍵的生產工作負載,因為穩定性與可預測性至關重要。 釘選功能還可讓您在開發階段測試您的應用程式於預發佈的執行階段版本上。
      沒有套件參考 n/a 如果沒有設定 azure-functions-runtime,你的 Python 3.13+ 應用程式就會在落後於最新版本的預設 Python 執行時上運行。 更新由函數定期進行。 此選項確保穩定性與廣泛相容性。 不過,最新功能和修正的存取會延遲,直到預設版本更新。
  • 相依性隔離:您的應用程式的相依性 (如grpcio 或 protobuf) 與背景工作角色的相依性完全隔離,避免版本衝突。 這個應用程式設定PYTHON_ISOLATE_WORKER_DEPENDENCIES對於運行在 Python 3.13 或更新版本的應用程式沒有影響。

  • 簡化 的 HTTP 串流 設定——不需要特殊應用程式設定。

  • 移除了對工作者擴充功能及共享記憶體功能的支援。

  • 執行時版本控制:你現在可以選擇性地將應用程式釘選或升級到特定的 Python 工作者版本,方法是參考你的 azure-functions-runtime-v1 中的 requirements.txt 套件。

    • 若不啟用版本控制,您的應用程式會運行在預設版本的 Python 執行時,而 Functions 會管理該執行環境。 您必須修改您的 requirements.txt 檔案,以請求最新發布版本、預發布版本,或將應用程式固定到特定版本的 Python 執行環境。

    • 您可以透過在 requirements.txt 檔案中加入對 Python 執行時套件的引用來啟用執行時版本控制,其中為該套件指派的值決定使用的執行時版本。

    • 避免將生產應用程式綁定到測試版(alpha、beta 或開發版)的執行時版本。

    • 要了解變更,請定期檢視 Python 執行時發布說明。

    • 下表顯示根據您 requirements.txt 檔案中此設定的版本值所進行的版本管理行為:

      版本 範例 行為
      沒有值設定 azure-functions-runtime-v1 你的 Python 3.13+ 應用程式運行於最新版本的 Functions Python 執行環境上。 這個選項最適合隨時掌握平台改進與功能,因為你的應用程式會自動收到最新的穩定執行時更新。
      已固定至特定版本 azure-functions-runtime-v1==1.2.0 你的 Python 3.13+ 應用程式會保持在固定的執行時間版本,且不會自動更新。 您必須手動更新釘選的版本,才能使用執行階段的新功能、修正與改進。 釘定建議用於關鍵的生產工作負載,因為穩定性與可預測性至關重要。 釘選功能還可讓您在開發階段測試您的應用程式於預發佈的執行階段版本上。
      沒有套件參考 n/a 如果沒有設定 azure-functions-runtime-v1,你的 Python 3.13+ 應用程式就會在落後於最新版本的預設 Python 執行時上運行。 更新由函數定期進行。 此選項確保穩定性與廣泛相容性。 不過,最新功能和修正的存取會延遲,直到預設版本更新。
  • 相依性隔離:您的應用程式的相依性 (如grpcio 或 protobuf) 與背景工作角色的相依性完全隔離,避免版本衝突。 這個應用程式設定PYTHON_ISOLATE_WORKER_DEPENDENCIES對於運行在 Python 3.13 或更新版本的應用程式沒有影響。

  • 移除了對工作者擴充功能及共享記憶體功能的支援。

可觀察性和測試

本節涵蓋logging、monitoring,以及 testing capabilities,幫助您除錯問題、追蹤效能,並確保Python功能應用程式的可靠性。

記錄和監視

Azure Functions 提供了一個根記錄器,你可以直接搭配 Python 內建的 logging 模組使用。 使用此記錄器撰寫的任何訊息,當您的應用程式在Azure運行時,會自動傳送至 Application Insights。

日誌功能讓你能在執行時擷取資訊並診斷問題,無需額外設定。

帶有 HTTP 觸發器的日誌範例

import logging
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.debug("Example debug log")
    logging.info("Example info log")
    logging.warning("Example warning")
    logging.error("Example error log")
    return func.HttpResponse("OK")
import logging
import azure.functions as func

app = func.FunctionApp()

@app.route(route="http_trigger")
def http_trigger(req) -> func.HttpResponse:
    logging.debug("Example debug log")
    logging.info("Example info log")
    logging.warning("Example warning")
    logging.error("Example error log")
    return func.HttpResponse("OK")

你可以使用完整的日誌層級(debug、info、warning、error、critical),這些層級會出現在Azure入口網站的日誌或應用程式洞察中。

欲了解更多關於入口網站中監測Azure Functions的資訊,請參閱 Monitor Azure Functions。

附註

若要在 Application Insights 中查看除錯日誌,則需進一步設定。 你可以在host.json 檔案中透過設定1為logLevel,並將trace設為debug或來啟用此功能。 預設情況下,除錯日誌不會在應用程式洞察中顯示。

從背景執行緒進行記錄

如果你的函式啟動新執行緒並需要從該執行緒進行日誌記錄,務必將參數傳 context 入執行緒。 context 包含執行緒區域儲存體和目前的 invocation_id,而且必須在工作執行緒上設定後者,日誌才能正確與函式執行建立關聯。

import logging
import threading
import azure.functions as func

def main(req: func.HttpRequest, context) -> func.HttpResponse:
    logging.info("Function started")
    t = threading.Thread(target=log_from_thread, args=(context,))
    t.start()
    return "okay"

def log_from_thread(context):
    # Associate the thread with the current invocation
    context.thread_local_storage.invocation_id = context.invocation_id  
    logging.info("Logging from a background thread")
import azure.functions as func
import logging
import threading

app = func.FunctionApp()

@app.route(route="http_trigger")
def http_trigger(req, context) -> func.HttpResponse:
    logging.info("Function started")
    t = threading.Thread(target=log_from_thread, args=(context,))
    t.start()
    return "okay"

def log_from_thread(context):
    # Associate the thread with the current invocation
    context.thread_local_storage.invocation_id = context.invocation_id  
    logging.info("Logging from a background thread")

設定自訂記錄器

當你需要更多記錄行為控制時,可以用 Python 設定自訂記錄器,例如自訂格式、日誌過濾或第三方整合。 要設定自訂記錄器,請使用 Python 的 logging.getLogger() 並自訂名稱,並根據需要新增處理程序或格式化器。

import logging

custom_logger = logging.getLogger('my_custom_logger')

OpenTelemetry 支援

Azure Functions for Python 也支援 OpenTelemetry,讓你能以標準化格式發送追蹤、指標和日誌。 使用 OpenTelemetry 對於分散式應用或情境特別有價值,當你想將遙測匯出到應用程式洞察外的工具(例如 Grafana 或 Jaeger)。

請參閱我們的 OpenTelemetry 快速入門Azure Functions (Python) 的設定說明與範例程式碼。

單元測試

用 pytest 來撰寫並執行你的函式單元測試。 你可以像測試其他 Python 程式碼一樣,使用標準測試框架來測試 Python 函式。 對於大多數綁定,你可以從套件中建立一個適當類別 azure.functions 的實例來建立模擬輸入物件。

使用 my_function 作為範例,以下是 HTTP 觸發函式的模擬測試:

首先,建立 <project_root>/function_app.py 檔案,並將函 my_function 式實作為 HTTP 觸發器。

# <project_root>/function_app.py
import azure.functions as func
import logging

app = func.FunctionApp()

# Define the HTTP trigger that accepts the ?value=<int> query parameter
# Double the value and return the result in HttpResponse
@app.function_name(name="my_function")
@app.route(route="hello")
def my_function(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Executing myfunction.')

    initial_value: int = int(req.params.get('value'))
    doubled_value: int = initial_value * 2

    return func.HttpResponse(
        body=f"{initial_value} * 2 = {doubled_value}",
        status_code=200
    )

您可以開始撰寫 HTTP 觸發程序的測試案例。

# <project_root>/test_my_function.py
import unittest
import azure.functions as func

from function_app import my_function

class TestFunction(unittest.TestCase):
  def test_my_function(self):
    # Construct a mock HTTP request.
    req = func.HttpRequest(method='GET',
                           body=None,
                           url='/api/my_function',
                           params={'value': '21'})
    # Call the function.
    func_call = main.build().get_user_function()
    resp = func_call(req)
    # Check the output.
    self.assertEqual(
        resp.get_body(),
        b'21 * 2 = 42',
    )

在你的 Python 虛擬環境資料夾中,執行以下指令來測試應用程式:

pip install pytest
pytest test_my_function.py

你會在終端機看到 pytest 結果,如下所示:

============================================================================================================ test session starts ============================================================================================================
collected 1 item                                                                                                                                                                                                                             

test_my_function.py .                                                                                                                                                                                                                  [100%] 
============================================================================================================= 1 passed in 0.24s ============================================================================================================= 

最佳化與進階主題

想了解更多如何優化你的 Python 函式應用程式,請參考以下文章:

欲了解更多關於函數的資訊,請參閱以下文章:

使用 Python 遇到問題嗎? 請告訴我們並提出問題。