Share via


攜帶相依性或協力廠商程式庫至 Azure Functions

在本文中,您會了解如何攜帶協力廠商相依性至函式應用程式。 協力廠商相依性的範例包括 JSON 檔案、二進位檔案和機器學習模型。

在本文中,您將學會如何:

  • 透過 Functions 程式碼專案帶入相依性
  • 透過掛接 Azure Fileshare 帶入相依性

從專案目錄帶入相依性

帶入相依性最簡單的其中一個方式是,將檔案/成品與函式應用程式程式碼放入函式專案目錄結構。 以下是 Python 函式專案中目錄範例的範例:

<project_root>/
 | - my_first_function/
 | | - __init__.py
 | | - function.json
 | | - example.py
 | - dependencies/
 | | - dependency1
 | - .funcignore
 | - host.json
 | - local.settings.json

將相依性放入函式應用程式專案目錄中的資料夾後,相依性資料夾會與程式碼一起部署。 因此,您的函式程式碼可以透過檔案系統 API 存取雲端中的相依性。

存取程式碼中的相依性

以下是存取並執行放入 <project_root>/ffmpeg_lib 目錄的 ffmpeg 相依性範例。

import logging

import azure.functions as func
import subprocess

FFMPEG_RELATIVE_PATH = "../ffmpeg_lib/ffmpeg"

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

    command = req.params.get('command')
    # If no command specified, set the command to help
    if not command:
        command = "-h"

    # context.function_directory returns the current directory in which functions is executed 
    ffmpeg_path = "/".join([str(context.function_directory), FFMPEG_RELATIVE_PATH])

    try:
        byte_output  = subprocess.check_output([ffmpeg_path, command])
        return func.HttpResponse(byte_output.decode('UTF-8').rstrip(),status_code=200)
    except Exception as e:
        return func.HttpResponse("Unexpected exception happened when executing ffmpeg. Error message:" + str(e),status_code=200)

注意

您可能需要使用 chmod,在 Linux 環境中提供 ffmpeg 二進位 Execute 的權限

帶入相依性最簡單的其中一個方式是,將檔案/成品與函式應用程式程式碼放入函式專案目錄結構。 以下是 Java 函式專案中目錄範例的範例:

<project_root>/
 | - src/
 | | - main/java/com/function
 | | | - Function.java
 | | - test/java/com/function
 | - artifacts/
 | | - dependency1
 | - host.json
 | - local.settings.json
 | - pom.xml

尤其如果是 JAVA,複製資源時,請務必將成品納入組建/目標檔案夾。 以下是如何在 Maven 中執行此動作的範例:

...
<execution>
    <id>copy-resources</id>
    <phase>package</phase>
    <goals>
        <goal>copy-resources</goal>
    </goals>
    <configuration>
        <overwrite>true</overwrite>
        <outputDirectory>${stagingDirectory}</outputDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}</directory>
                <includes>
                    <include>host.json</include>
                    <include>local.settings.json</include>
                    <include>artifacts/**</include>
                </includes>
            </resource>
        </resources>
    </configuration>
</execution>
...

將相依性放入函式應用程式專案目錄中的資料夾後,相依性資料夾會與程式碼一起部署。 因此,您的函式程式碼可以透過檔案系統 API 存取雲端中的相依性。

存取程式碼中的相依性

以下是存取並執行放入 <project_root>/ffmpeg_lib 目錄的 ffmpeg 相依性範例。

public class Function {
    final static String BASE_PATH = "BASE_PATH";
    final static String FFMPEG_PATH = "/artifacts/ffmpeg/ffmpeg.exe";
    final static String HELP_FLAG = "-h";
    final static String COMMAND_QUERY = "command";

    @FunctionName("HttpExample")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET, HttpMethod.POST},
                authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) throws IOException{
        context.getLogger().info("Java HTTP trigger processed a request.");

        // Parse query parameter
        String flags = request.getQueryParameters().get(COMMAND_QUERY);

        if (flags == null || flags.isBlank()) {
            flags = HELP_FLAG;
        }

        Runtime rt = Runtime.getRuntime();
        String[] commands = { System.getenv(BASE_PATH) + FFMPEG_PATH, flags};
        Process proc = rt.exec(commands);

        BufferedReader stdInput = new BufferedReader(new 
        InputStreamReader(proc.getInputStream()));

        String out = stdInput.lines().collect(Collectors.joining("\n"));
        if(out.isEmpty()) {
            BufferedReader stdError = new BufferedReader(new 
                InputStreamReader(proc.getErrorStream()));
            out = stdError.lines().collect(Collectors.joining("\n"));
        }
        return request.createResponseBuilder(HttpStatus.OK).body(out).build();

    }

注意

若要此程式碼片段在 Azure 中運作,您必須將 "BASE_PATH" 的自訂應用程式設定的值指定為 "/home/site/wwwroot"

掛接檔案共用並攜帶相依性

在 Linux 上執行函式應用程式時,系統提供另一種方式帶入協力廠商相依性。 函式讓您掛接 Azure 檔案中託管的檔案共用。 您想從應用程式程式碼分離相依性或成品時,請考慮此方法。

首先,請建立 Azure 儲存體帳戶。 在帳戶中,您一樣需要在 Azure 檔案中建立檔案共用。 若要建立這些資源,請遵循本指南

建立儲存體帳戶和檔案共用後,請使用 az webapp config storage-account add 命令來將檔案共用附加至函式應用程式,如下列範例所示。

az webapp config storage-account add \
  --name < Function-App-Name > \
  --resource-group < Resource-Group > \
  --subscription < Subscription-Id > \
  --custom-id < Unique-Custom-Id > \
  --storage-type AzureFiles \
  --account-name < Storage-Account-Name > \
  --share-name < File-Share-Name >  \
  --access-key < Storage-Account-AccessKey > \
  --mount-path </path/to/mount>
旗標
custom-id 任何唯一字串
storage-type 目前僅支援 AzureFiles
share-name 預先存在的共用
mount-path 共用在容器中可存取的路徑。 值必須是 /dir-name 格式,且不能以 /home 開頭

您可以在這裡找到更多修改/刪除檔案共用設定的命令

上傳相依性至 Azure 檔案

上傳相依性至 Azure 檔案的其中一個選項是透過 Azure 入口網站。 如需使用入口網站上傳相依性的指示,請參閱本指南。 其他上傳相依性至 Azure 檔案的選項是,透過 Azure CLIPowerShell

存取程式碼中的相依性

在檔案共用中上傳相依性後,您可以從程式碼存取相依性。 指定的 mount-path (例如 /path/to/mount) 提供掛接的共用。 您可以使用檔案系統 API 存取目標目錄。

下列範例示範可存取 ffmpeg 程式庫的 HTTP 觸發程式碼,而此程式碼儲存在掛接的檔案共用中。

import logging

import azure.functions as func
import subprocess 

FILE_SHARE_MOUNT_PATH = os.environ['FILE_SHARE_MOUNT_PATH']
FFMPEG = "ffmpeg"

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

    command = req.params.get('command')
    # If no command specified, set the command to help
    if not command:
        command = "-h"

    try:
        byte_output  = subprocess.check_output(["/".join(FILE_SHARE_MOUNT_PATH, FFMPEG), command])
        return func.HttpResponse(byte_output.decode('UTF-8').rstrip(),status_code=200)
    except Exception as e:
        return func.HttpResponse("Unexpected exception happened when executing ffmpeg. Error message:" + str(e),status_code=200)

部署此程式碼至 Azure 中的函式應用程式後,請使用名為 FILE_SHARE_MOUNT_PATH 的索引鍵和掛接檔案共用路徑的值 (在此範例中為 /azure-files-share) 來建立應用程式設定。 若要執行本機偵錯,請以本機電腦中儲存相依性位置的檔案路徑來填入 FILE_SHARE_MOUNT_PATH。 以下是使用 local.settings.json 設定 FILE_SHARE_MOUNT_PATH 的範例:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "FILE_SHARE_MOUNT_PATH" : "PATH_TO_LOCAL_FFMPEG_DIR"
  }
}

下一步