azure-functions-python-samples icon indicating copy to clipboard operation
azure-functions-python-samples copied to clipboard

How to import a custom python module file into azure function

Open infact opened this issue 5 years ago • 2 comments

How to import a custom python module file into azure function. My python class needs to import my custom class. For instance

import os
import time
from optparse import OptionParser
**from mlutil import HTMLPath**

How can I upload/where to upload my mlutil.py file so that my import from mlutil class won't throw error in my azure function ?

infact avatar Sep 18 '20 03:09 infact

Have you looked at this section in the docs? https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python#import-behavior

__app__
| - my_first_function
| | - __init__.py
| | - function.json
| | - example.py
| - my_second_function
| | - __init__.py
| | - function.json
| - shared_code
| | - my_first_helper_function.py
| | - my_second_helper_function.py
| - host.json
| - requirements.txt
| - Dockerfile
tests

You can import modules in your function code using both explicit relative and absolute references. Based on the folder structure shown above, the following imports work from within the function file __app__\my_first_function\__init__.py:

from . import example #(explicit relative)

from ..shared_code import my_first_helper_function #(explicit relative)

from __app__ import shared_code #(absolute)

import __app__.shared_code #(absolute)

snobu avatar Sep 18 '20 08:09 snobu

Hi, adding to the above solution by @snobu, if you want to use absolute import and have nested directories, you can add your packages / module directories into python system variables using import sys sys.path.append('path to package or module with azure function directory as the root directory') The root directory is the directory containing the function.json file

t-souravgoel avatar Jun 12 '21 21:06 t-souravgoel