Import custom modules in azure python function

Question:

I am building a python function I and I need to add my custom module in the code. My azure function looks like this:

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. This function works perfectly in the local environment using Visual Studio Code. However, when I deploy and run it, it throws 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. I am not sure what am I missing. Please not since its not a standard library I cannot add it in the 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.

Asked By: Hassan Abbas

||

Answers:

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}")]
Answered By: Hassan Abbas

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:

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

Answered By: Raphael Balogo

See also the offical documentation regarding Import Behavior in Functions for Python.

Answered By: Ken Jiiii