Azure Functions Python 開發人員指南Azure Functions Python developer guide

本文是使用 Python 開發 Azure Functions 的簡介。This article is an introduction to developing Azure Functions using Python. 本文假設您已閱讀過下列 Azure Functions 開發人員指南The content below assumes that you've already read the Azure Functions developers guide.

如需 Python 中的獨立函式範例專案,請參閱 Python 函式範例For standalone Function sample projects in Python, see the Python Functions samples.

程式設計模型Programming model

Azure Functions 預期函式在 Python 腳本中是可處理輸入並產生輸出的無狀態方法。Azure Functions expects a function to be a stateless method in your Python script that processes input and produces output. 根據預設,執行時間會預期方法會實作為在 __init__.py 檔案中稱為 main() 的全域方法。By default, the runtime expects the method to be implemented as a global method called main() in the __init__.py file. 您也可以指定替代的進入點You can also specify an alternate entry point.

來自觸發程式和系結的資料,會使用函式json檔案中定義的 name 屬性,透過方法屬性系結至函式。Data from triggers and bindings is bound to the function via method attributes using the name property defined in the function.json file. 例如,下面的_函數. json_描述由名為 req的 HTTP 要求所觸發的簡單函式:For example, the function.json below describes a simple function triggered by an HTTP request named req:

{
  "bindings": [
    {
      "name": "req",
      "direction": "in",
      "type": "httpTrigger",
      "authLevel": "anonymous"
    },
    {
      "name": "$return",
      "direction": "out",
      "type": "http"
    }
  ]
}

__init__.py 檔案包含下列函式程式碼:The __init__.py file contains the following function code:

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

您也可以使用 Python 類型注釋,在函式中明確宣告屬性類型和傳回類型。you can also explicitly declare the attribute types and return type in the function using Python type annotations. 這可協助您使用許多 Python 程式碼編輯器所提供的 intellisense 和自動完成功能。This helps you use the intellisense and autocomplete features provided by many Python code editors.

import azure.functions


def main(req: azure.functions.HttpRequest) -> str:
    user = req.params.get('user')
    return f'Hello, {user}!'

請使用 azure.functions.* 套件中所包含的 Python 註釋,以將輸入和輸出繫結至方法。Use the Python annotations included in the azure.functions.* package to bind input and outputs to your methods.

替代進入點Alternate entry point

您可以選擇性地在函數. json檔案中指定 scriptFileentryPoint 屬性,以變更函式的預設行為。You can change the default behavior of a function by optionally specifying the scriptFile and entryPoint properties in the function.json file. 例如 _,下列函_式會指示執行時間在_main.py_檔案中使用 customentry() 方法,做為您的 Azure 函式的進入點。For example, the function.json below tells the runtime to use the customentry() method in the main.py file, as the entry point for your Azure Function.

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

資料夾結構Folder structure

Python 函式專案的建議資料夾結構如下列範例所示:The recommended folder structure for a Python Functions project looks like the following example:

 __app__
 | - MyFirstFunction
 | | - __init__.py
 | | - function.json
 | | - example.py
 | - MySecondFunction
 | | - __init__.py
 | | - function.json
 | - SharedCode
 | | - myFirstHelperFunction.py
 | | - mySecondHelperFunction.py
 | - host.json
 | - requirements.txt
 tests

主要專案資料夾(__應用程式__)可以包含下列檔案:The main project folder (__app__) can contain the following files:

  • 本機執行時,用來儲存應用程式設定和連接字串的。local.settings.json: Used to store app settings and connection strings when running locally. 此檔案不會發行至 Azure。This file doesn't get published to Azure. 若要深入瞭解,請參閱local. settings. fileTo learn more, see local.settings.file.
  • 需求 .txt:包含在發佈至 Azure 時,系統所安裝的套件清單。requirements.txt: Contains the list of packages the system installs when 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. 在本機執行時,不支援所有選項。Not all options are supported when running locally. 若要深入瞭解,請參閱host. jsonTo learn more, see host.json.
  • funcignore:(選擇性)宣告不應發行至 Azure 的檔案。funcignore: (Optional) declares files that shouldn't get published to Azure.
  • .gitignore:(選擇性)宣告從 git 存放庫排除的檔案,例如 local. settings. json。gitignore: (Optional) declares files that are excluded from a git repo, such as local.settings.json.

每個函式都具有本身的程式碼檔案和繫結設定檔 (function.json)。Each function has its own code file and binding configuration file (function.json).

共用程式碼應該保存在 __應用程式__的個別資料夾中。Shared code should be kept in a separate folder in __app__. 若要參考 SharedCode 資料夾中的模組,您可以使用下列語法:To reference modules in the SharedCode folder, you can use the following syntax:

from __app__.SharedCode import myFirstHelperFunction

若要參考函數的本機模組,您可以使用相對的匯入語法,如下所示:To reference modules local to a function, you can use the relative import syntax as follows:

from . import example

將您的專案部署至 Azure 中的函式應用程式時, FunctionApp資料夾的完整內容應該包含在套件中,而不是資料夾本身。When deploying your project to a function app in Azure, the entire content of the FunctionApp folder should be included in the package, but not the folder itself. 我們建議您在與專案資料夾不同的資料夾中維護您的測試,在此範例中 testsWe recommend that you maintain your tests in a folder separate from the project folder, in this example tests. 這可讓您不需要將測試程式碼與應用程式一起部署。This keeps you from deploying test code with your app. 如需詳細資訊,請參閱單元測試For more information, see Unit Testing.

觸發程式和輸入Triggers and Inputs

在 Azure Functions 中輸入會分成兩個類別:觸發程序輸入和額外的輸入。Inputs are divided into two categories in Azure Functions: trigger input and additional input. 雖然它們在 function.json 檔案中不同,但在 Python 程式碼中的使用方式是相同的。Although they are different in the function.json file, usage is identical in Python code. 在本機執行時,觸發程式和輸入來源的連接字串或密碼會對應至 local.settings.json 檔案中的值,以及在 Azure 中執行時的應用程式設定。Connection strings or secrets for trigger and input sources map to values in the local.settings.json file when running locally, and the application settings when running in Azure.

例如,下列程式碼示範兩者之間的差異:For example, the following code demonstrates the difference between the two:

// function.json
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "req",
      "direction": "in",
      "type": "httpTrigger",
      "authLevel": "anonymous",
      "route": "items/{id}"
    },
    {
      "name": "obj",
      "direction": "in",
      "type": "blob",
      "path": "samples/{id}",
      "connection": "AzureWebJobsStorage"
    }
  ]
}
// local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "<azure-storage-connection-string>"
  }
}
# __init__.py
import azure.functions as func
import logging


def main(req: func.HttpRequest,
         obj: func.InputStream):

    logging.info(f'Python HTTP triggered function processed: {obj.read()}')

叫用此函式時,HTTP 要求會以 req 形式傳遞至函式。When the function is invoked, the HTTP request is passed to the function as req. 系統會根據路由 URL 中的_識別碼_從 Azure Blob 儲存體中抓取專案,並在函式主體中以 obj 的形式提供。An entry will be retrieved from the Azure Blob Storage based on the ID in the route URL and made available as obj in the function body. 在這裡,指定的儲存體帳戶是在中找到的連接字串,這是函數應用程式所使用的相同儲存體帳戶。Here the storage account specified is the connection string found in , which is the same storage account used by the function app.

referenceOutputs

輸出可以使用傳回值和輸出參數來表示。Output can be expressed both in return value and output parameters. 如果只有一個輸出,我們建議使用傳回的值。If there's only one output, we recommend using the return value. 若為多個輸出,您必須使用輸出參數。For multiple outputs, you'll have to use output parameters.

若要使用函式的傳回值作為輸出繫結的值,應該將 name 中的繫結 $return 屬性設定為 function.jsonTo use the return value of a function as the value of an output binding, the name property of the binding should be set to $return in function.json.

若要產生多個輸出,請使用azure.functions.Out介面提供的 set() 方法,將值指派給系結。To produce multiple outputs, use the set() method provided by the azure.functions.Out interface to assign a value to the binding. 例如,下列函式可以將訊息推送至佇列,同時也會傳回 HTTP 回應。For example, the following function can push a message to a queue and also return an HTTP response.

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "req",
      "direction": "in",
      "type": "httpTrigger",
      "authLevel": "anonymous"
    },
    {
      "name": "msg",
      "direction": "out",
      "type": "queue",
      "queueName": "outqueue",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "$return",
      "direction": "out",
      "type": "http"
    }
  ]
}
import azure.functions as func


def main(req: func.HttpRequest,
         msg: func.Out[func.QueueMessage]) -> str:

    message = req.params.get('body')
    msg.set(message)
    return message

記錄Logging

可以透過函式應用程式中的根 logging 處理常式來存取 Azure Functions 執行階段記錄器。Access to the Azure Functions runtime logger is available via a root logging handler in your function app. 這個記錄器會繫結至 Application Insights,並可讓您將函式執行期間遇到的警告和錯誤加上旗標。This logger is tied to Application Insights and allows you to flag warnings and errors encountered during the function execution.

下列範例在透過 HTTP 觸發程序叫用函式時,會記錄一則資訊訊息。The following example logs an info message when the function is invoked via an HTTP trigger.

import logging


def main(req):
    logging.info('Python HTTP trigger function processed a request.')

其他的記錄方法可讓您在不同追蹤層級寫入主控台記錄中︰Additional logging methods are available that let you write to the console at different trace levels:

方法Method 描述Description
critical(_message_) 在根記錄器上寫入層級為 CRITICAL (重大) 的訊息。Writes a message with level CRITICAL on the root logger.
error(_message_) 在根記錄器上寫入層級為 ERROR (錯誤) 的訊息。Writes a message with level ERROR on the root logger.
warning(_message_) 在根記錄器上寫入層級為 WARNING (警告) 的訊息。Writes a message with level WARNING on the root logger.
info(_message_) 在根記錄器上寫入層級為 INFO (資訊) 的訊息。Writes a message with level INFO on the root logger.
debug(_message_) 在根記錄器上寫入層級為 DEBUG (偵錯) 的訊息。Writes a message with level DEBUG on the root logger.

若要深入瞭解記錄,請參閱監視 Azure FunctionsTo learn more about logging, see Monitor Azure Functions.

HTTP 觸發程式和系結HTTP Trigger and bindings

HTTP 觸發程式定義于 function. jon 檔案中。The HTTP trigger is defined in the function.jon file. 系結的 name 必須符合函式中的具名引數。The name of the binding must match the named parameter in the function. 在先前的範例中,會使用 req 的系結名稱。In the previous examples, a binding name req is used. 這個參數是HttpRequest物件,而且會傳回HttpResponse物件。This parameter is an HttpRequest object, and an HttpResponse object is returned.

您可以從HttpRequest物件取得要求標頭、查詢參數、路由參數和訊息內文。From the HttpRequest object, you can get request headers, query parameters, route parameters, and the message body.

下列範例來自Python 的 HTTP 觸發程式範本The following example is from the HTTP trigger template for Python.

def main(req: func.HttpRequest) -> func.HttpResponse:
    headers = {"my-http-header": "some-value"}

    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}!", headers=headers)
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             headers=headers, status_code=400
        )

在此函數中,會從HttpRequest物件的 params 參數取得 name 查詢參數的值。In this function, the value of the name query parameter is obtained from the params parameter of the HttpRequest object. JSON 編碼的訊息本文會使用 get_json 方法來讀取。The JSON-encoded message body is read using the get_json method.

同樣地,您可以在傳回的HttpResponse物件中設定回應訊息的 status_codeheadersLikewise, you can set the status_code and headers for the response message in the returned HttpResponse object.

並行Concurrency

根據預設,Python 執行時間一次只能處理一個函式的調用。By default, the Functions Python runtime can only process one invocation of a function at a time. 此並行層級可能不足以符合下列一或多個條件:This concurrency level might not be sufficient under one or more of the following conditions:

  • 您正嘗試處理同時進行的多個調用。You're trying to handle a number of invocations being made at the same time.
  • 您正在處理大量 i/o 事件。You're processing a large number of I/O events.
  • 您的應用程式與 i/o 系結。Your application is I/O bound.

在這些情況下,您可以透過非同步方式執行,並使用多個語言背景工作進程來改善效能。In these situations, you can improve performance by running asynchronously and by using multiple language worker processes.

非同步處理Async

建議您使用 async def 語句,讓函式以非同步協同程式的方式執行。We recommend that you use the async def statement to make your function run as an asynchronous coroutine.

# Runs with asyncio directly

async def main():
    await some_nonblocking_socket_io_op()

main() 函式是同步的(沒有 async 限定詞)時,函數會自動在 asyncio 執行緒集區中執行。When the main() function is synchronous (without the async qualifier), the function is automatically run in an asyncio thread-pool.

# Runs in an asyncio thread-pool

def main():
    some_blocking_socket_io()

使用多個語言工作者進程Use multiple language worker processes

根據預設,每個函式主控制項實例都有單一的語言工作者進程。By default, every Functions host instance has a single language worker process. 不過,支援每個主控制項實例有多個語言工作者進程。However there's support to have multiple language worker processes per host instance. 接著,函式呼叫可以平均分散在這些語言工作者進程中。Function invocations can then be evenly distributed among these language worker processes. 請使用FUNCTIONS_WORKER_PROCESS_COUNT應用程式設定來變更此值。Use the FUNCTIONS_WORKER_PROCESS_COUNT application setting to change this value.

ContextContext

若要在執行期間取得函數的調用內容,請在其簽章中包含context引數。To get the invocation context of a function during execution, include the context argument in its signature.

例如︰For example:

import azure.functions


def main(req: azure.functions.HttpRequest,
         context: azure.functions.Context) -> str:
    return f'{context.invocation_id}'

內容類具有下列字串屬性:The Context class has the following string attributes:

function_directory
函式執行所在的目錄。The directory in which the function is running.

function_name
函式的名稱。Name of the function.

invocation_id
目前函式引動的識別碼。ID of the current function invocation.

全域變數Global variables

不保證會保留您應用程式的狀態,以供未來執行之用。It is not guaranteed that the state of your app will be preserved for future executions. 不過,Azure Functions 執行時間通常會針對相同應用程式的多個執行重複使用相同的進程。However, the Azure Functions runtime often reuses the same process for multiple executions of the same app. 為了快取昂貴計算的結果,請將它宣告為全域變數。In order to cache the results of an expensive computation, declare it as a global variable.

CACHED_DATA = None


def main(req):
    global CACHED_DATA
    if CACHED_DATA is None:
        CACHED_DATA = load_json()

    # ... use CACHED_DATA in code

環境變數Environment variables

在函數中,應用程式設定(例如服務連接字串)在執行期間會公開為環境變數。In Functions, application settings, such as service connection strings, are exposed as environment variables during execution. 您可以藉由宣告 import os,然後使用 setting = os.environ["setting-name"],來存取這些設定。You can access these settings by declaring import os and then using, setting = os.environ["setting-name"].

下列範例會取得應用程式設定,並將金鑰命名為 myAppSettingThe following example gets the application setting, with the key named myAppSetting:

import logging
import os
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:

    # Get the setting named 'myAppSetting'
    my_app_setting_value = os.environ["myAppSetting"]
    logging.info(f'My app setting value:{my_app_setting_value}')

就本機開發而言,應用程式設定會保留在本機的設定 json 檔案中For local development, application settings are maintained in the local.settings.json file.

Python 版本Python version

目前,Azure Functions 支援 Python 3.6. x 和 3.7. x (官方 CPython 散發套件)。Currently, Azure Functions supports both Python 3.6.x and 3.7.x (official CPython distributions). 在本機執行時,執行時間會使用可用的 Python 版本。When running locally, the runtime uses the available Python version. 若要在 Azure 中建立函數應用程式時要求特定的 Python 版本,請使用az functionapp create命令的 --runtime-version 選項。To request a specific Python version when you create your function app in Azure, use the --runtime-version option of the az functionapp create command.

封裝管理Package management

使用 Azure Functions Core Tools 或 Visual Studio Code 在本機進行開發時,將所需的套件名稱和版本新增到 requirements.txt 檔案,並使用 pip 進行安裝。When developing locally using the Azure Functions Core Tools or Visual Studio Code, add the names and versions of the required packages to the requirements.txt file and install them using pip.

例如,可以使用下列要求和 pip 命令從 PyPl 安裝 requests 套件。For example, the following requirements file and pip command can be used to install the requests package from PyPI.

requests==2.19.1
pip install -r requirements.txt

發行到 AzurePublishing to Azure

當您準備好要發行時,請確定所有公開可用的相依性都列在 [需求 .txt] 檔案中,該檔案位於專案目錄的根目錄中。When you're ready to publish, make sure that all your publicly available dependencies are listed in the requirements.txt file, which is located at the root of your project directory.

從發行排除的專案檔和資料夾(包括虛擬環境資料夾)會列在 funcignore 檔案中。Project files and folders that are excluded from publishing, including the virtual environment folder, are listed in the .funcignore file.

有三個組建動作支援將 Python 專案發行至 Azure:There are three build actions supported for publishing your Python project to Azure:

  • 遠端組建:根據需求 .txt 檔案的內容,從遠端取得相依性。Remote build: Dependencies are obtained remotely based on the contents of the requirements.txt file. 遠端組建」是建議的組建方法。Remote build is the recommended build method. [遠端] 也是 Azure 工具的預設組建選項。Remote is also the default build option of Azure tooling.
  • 本機組建:根據需求 .txt 檔案的內容,在本機取得相依性。Local build: Dependencies are obtained locally based on the contents of the requirements.txt file.
  • 自訂相依性:您的專案使用我們的工具無法公開使用的套件。Custom dependencies: Your project uses packages not publicly available to our tools. (需要 Docker)。(Requires Docker.)

若要建立您的相依性,並使用持續傳遞(CD)系統發佈,請使用 Azure PipelinesTo build your dependencies and publish using a continuous delivery (CD) system, use Azure Pipelines.

遠端組建Remote build

根據預設,當您使用下列func Azure functionapp publish命令將 Python 專案發佈至 Azure 時,Azure Functions Core Tools 會要求遠端組建。By default, the Azure Functions Core Tools requests a remote build when you use the following func azure functionapp publish command to publish your Python project to Azure.

func azure functionapp publish <APP_NAME>

在 Azure 中,請記得以您的函式應用程式名稱取代 <APP_NAME>Remember to replace <APP_NAME> with the name of your function app in Azure.

Visual Studio Code 的 Azure Functions 延伸模組預設也會要求遠端組建。The Azure Functions Extension for Visual Studio Code also requests a remote build by default.

本機組建Local build

您可以使用下列func azure functionapp publish命令,以本機組建發行,以防止執行遠端組建。You can prevent doing a remote build by using the following func azure functionapp publish command to publish with a local build.

func azure functionapp publish <APP_NAME> --build local

在 Azure 中,請記得以您的函式應用程式名稱取代 <APP_NAME>Remember to replace <APP_NAME> with the name of your function app in Azure.

使用 [--build local] 選項,就會從需求 .txt 檔案讀取專案相依性,並在本機下載並安裝那些依存的套件。Using the --build local option, project dependencies are read from the requirements.txt file and those dependent packages are downloaded and installed locally. 專案檔和相依性會從您的本機電腦部署至 Azure。Project files and dependencies are deployed from your local computer to Azure. 這會導致將較大的部署套件上傳至 Azure。This results in a larger deployment package being uploaded to Azure. 如果基於某些原因,核心工具無法取得您的需求 .txt 檔案中的相依性,您必須使用 [自訂相依性] 選項來進行發佈。If for some reason, dependencies in your requirements.txt file can't be acquired by Core Tools, you must use the custom dependencies option for publishing.

自訂相依性Custom dependencies

如果您的專案使用我們的工具無法公開使用的套件,您可以將它們放在 __應用程式__/. python_packages 目錄中,讓它們可供您的應用程式使用。If your project uses packages not publicly available to our tools, you can make them available to your app by putting them in the __app__/.python_packages directory. 在發佈之前,請執行下列命令以在本機安裝相依性:Before publishing, run the following command to install the dependencies locally:

pip install  --target="<PROJECT_DIR>/.python_packages/lib/site-packages"  -r requirements.txt

使用自訂相依性時,您應該使用 [--no-build 發佈] 選項,因為您已經安裝相依性。When using custom dependencies, you should use the --no-build publishing option, since you have already installed the dependencies.

func azure functionapp publish <APP_NAME> --no-build

在 Azure 中,請記得以您的函式應用程式名稱取代 <APP_NAME>Remember to replace <APP_NAME> with the name of your function app in Azure.

單元測試Unit Testing

以 Python 撰寫的函式可以使用標準測試架構來測試,就像其他 Python 程式碼一樣。Functions written in Python can be tested like other Python code using standard testing frameworks. 對於大部分的系結,您可以從 azure.functions 封裝建立適當類別的實例,以建立模擬輸入物件。For most bindings, it's possible to create a mock input object by creating an instance of an appropriate class from the azure.functions package. 因為azure.functions套件無法立即使用,請務必透過您的 requirements.txt 檔案加以安裝,如上面的封裝管理一節中所述。Since the azure.functions package is not immediately available, be sure to install it via your requirements.txt file as described in the package management section above.

例如,下列是 HTTP 觸發函式的模擬測試:For example, following is a mock test of an HTTP triggered function:

{
  "scriptFile": "__init__.py",
  "entryPoint": "my_function",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}
# __app__/HttpTrigger/__init__.py
import azure.functions as func
import logging

def my_function(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}")
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )
# tests/test_httptrigger.py
import unittest

import azure.functions as func
from __app__.HttpTrigger 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/HttpTrigger',
            params={'name': 'Test'})

        # Call the function.
        resp = my_function(req)

        # Check the output.
        self.assertEqual(
            resp.get_body(),
            b'Hello Test',
        )

以下是另一個範例,其中包含已觸發佇列的函式:Here is another example, with a queue triggered function:

{
  "scriptFile": "__init__.py",
  "entryPoint": "my_function",
  "bindings": [
    {
      "name": "msg",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "python-queue-items",
      "connection": "AzureWebJobsStorage"
    }
  ]
}
# __app__/QueueTrigger/__init__.py
import azure.functions as func

def my_function(msg: func.QueueMessage) -> str:
    return f'msg body: {msg.get_body().decode()}'
# tests/test_queuetrigger.py
import unittest

import azure.functions as func
from __app__.QueueTrigger import my_function

class TestFunction(unittest.TestCase):
    def test_my_function(self):
        # Construct a mock Queue message.
        req = func.QueueMessage(
            body=b'test')

        # Call the function.
        resp = my_function(req)

        # Check the output.
        self.assertEqual(
            resp,
            'msg body: test',
        )

暫存檔案Temporary files

tempfile.gettempdir() 方法會傳回在 Linux 上 /tmp的暫存資料夾。The tempfile.gettempdir() method returns a temporary folder, which on Linux is /tmp. 您的應用程式可以使用此目錄來儲存您的函式在執行期間所產生及使用的暫存檔案。Your application can use this directory to store temporary files generated and used by your functions during execution.

重要

寫入臨時目錄的檔案不保證會在調用之間保存。Files written to the temporary directory aren't guaranteed to persist across invocations. 在相應放大期間,暫存檔案不會在實例之間共用。During scale out, temporary files aren't shared between instances.

下列範例會在臨時目錄中建立名為的暫存檔案(/tmp):The following example creates a named temporary file in the temporary directory (/tmp):

import logging
import azure.functions as func
import tempfile
from os import listdir

#---
   tempFilePath = tempfile.gettempdir()   
   fp = tempfile.NamedTemporaryFile()     
   fp.write(b'Hello world!')              
   filesDirListInTemp = listdir(tempFilePath)     

我們建議您將測試維護在與專案資料夾不同的資料夾中。We recommend that you maintain your tests in a folder separate from the project folder. 這可讓您不需要將測試程式碼與應用程式一起部署。This keeps you from deploying test code with your app.

已知問題和常見問題集Known issues and FAQ

所有已知問題和功能要求則會使用 GitHub 問題清單追蹤。All known issues and feature requests are tracked using GitHub issues list. 如果您遇到問題,但在 GitHub 中卻找不到此問題,請開啟新的問題,並包含問題的詳細說明。If you run into a problem and can't find the issue in GitHub, open a new issue and include a detailed description of the problem.

跨原始資源共用Cross-origin resource sharing

Azure Functions 支援跨原始來源資源分享(CORS)。Azure Functions supports cross-origin resource sharing (CORS). CORS 會在入口網站中以及透過Azure CLI進行設定。CORS is configured in the portal and through the Azure CLI. CORS 允許的原始來源清單適用于函數應用層級。The CORS allowed origins list applies at the function app level. 在啟用 CORS 的情況下,回應會包含 Access-Control-Allow-Origin 標頭。With CORS enabled, responses include the Access-Control-Allow-Origin header. 如需詳細資訊,請參閱 跨原始來源資源分享(英文)。For more information, see Cross-origin resource sharing.

Python 函式應用程式目前不支援允許的原始來源清單。The allowed origins list isn't currently supported for Python function apps. 由於這項限制,您必須在 HTTP 函式中明確設定 Access-Control-Allow-Origin 標頭,如下列範例所示:Because of this limitation, you must expressly set the Access-Control-Allow-Origin header in your HTTP functions, as shown in the following example:

def main(req: func.HttpRequest) -> func.HttpResponse:

    # Define the allow origin headers.
    headers = {"Access-Control-Allow-Origin": "https://contoso.com"}

    # Set the headers in the response.
    return func.HttpResponse(
            f"Allowed origin '{headers}'.",
            headers=headers, status_code=200
    )

請確定您也更新了函數. json,以支援 OPTIONS HTTP 方法:Make sure that you also update your function.json to support the OPTIONS HTTP method:

    ...
      "methods": [
        "get",
        "post",
        "options"
      ]
    ...

Chrome 瀏覽器會使用這個方法來協調允許的原始來源清單。This method is used by the Chrome browser to negotiate the allowed origins list.

後續步驟Next steps

如需詳細資訊,請參閱下列資源:For more information, see the following resources: