简体   繁体   English

在 azure python function 中导入自定义模块

[英]Import custom modules in azure python function

I am building a python function I and I need to add my custom module in the code.我正在构建一个 python function 我需要在代码中添加我的自定义模块。 My azure function looks like this:我的 azure function 看起来像这样:

import logging
import sys
from sys import path
import os
import time
sys.path.insert(0, './myFunctionFolderName') // Try to insert it as a standard python library. 

import azure.functions as func
from myCustomModule.models import someFunctionName


def main(req: func.HttpRequest) -> func.HttpResponse:
    name = "My new function"
    testing_variable = someFunctionName()
    return func.HttpResponse(f"Function executed {name}")]

What I have done is inserted my function folder as a standard path so python looks for the libraries in that folder as well.我所做的是将我的 function 文件夹作为标准路径插入,因此 python 也会在该文件夹中查找库。 This function works perfectly in the local environment using Visual Studio Code.此 function 使用 Visual Studio Code 在本地环境中完美运行。 However, when I deploy and run it, it throws myCustomModule not found.但是,当我部署并运行它时,它会抛出myCustomModule not found。 Another piece of information is that I cannot access Kudu (terminal) since it is not suppored on my consumption plan for Linux.另一条信息是我无法访问 Kudu(终端),因为我的 Linux 的消费计划不支持它。 I am not sure what am I missing.我不确定我错过了什么。 Please not since its not a standard library I cannot add it in the requirements.txt.请不要,因为它不是标准库,我无法将它添加到 requirements.txt 中。 Also note, that my function folder has my function script file and my custom module so they are in the same folder as it should be in the azure python template. Also note, that my function folder has my function script file and my custom module so they are in the same folder as it should be in the azure python template.

Use an absolute path rather than the relative paths.使用绝对路径而不是相对路径。

Following worked for me以下为我工作

import logging
import sys
from sys import path
import os
import time

dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, dir_path)

import azure.functions as func
from myCustomModule.models import someFunctionName

def main(req: func.HttpRequest) -> func.HttpResponse:
    name = "My new function"
    testing_variable = someFunctionName()
    return func.HttpResponse(f"Function executed {name}")]

A simpler solution than this response is to explicitly tell python to use local import adding a dot before the custom module import, like this:比此响应更简单的解决方案是明确告诉 python 使用本地导入,在自定义模块导入之前添加一个点,如下所示:

import logging
import sys
from sys import path
import os
import time    
import azure.functions as func

from .myCustomModule.models import someFunctionName

It works with Azure Functions它适用于 Azure 功能

See also the offical documentation regarding Import Behavior in Functions for Python.另请参阅有关 Python 的函数中的导入行为的官方文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM