Mueez Ahmad
Mueez Ahmad

Reputation: 43

Azure Functions with Multiple Python Files

I am unable to import my other python file in the init.py file. I have tried importing that according to the same way as mentioned in the documentation.

https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#import-behavior

This is my init.py file:

    import logging

    import azure.functions as func
    from . import test


    def main(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
        print("test")
        num = sum_num(2, 3)
        print(num)
        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}. This HTTP triggered function executed successfully.")
        else:
            return func.HttpResponse(
                "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
                status_code=200
            )

this is my test.py file with very basic sum function:

    def sum_num(val1, val2):
        print("inside function")
        return val1 + val2

Please help me out how to import this sum_num function in my init.py file.

the folder structure is also fine as you can see:

Error i am getting in the logs

Upvotes: 4

Views: 5652

Answers (2)

Timbus Calin
Timbus Calin

Reputation: 14983

BEWARE

The first solution presented by Abdul works indeed : from . import test, provided that you have a test.py at the same level with the __init__.py.

However, the solution from .test import sum_num does not work.

I both solutions and the latter does not work.

Indeed, according to the documentation, the only way for relative import is this one (see in the docs):

 from . import example #(relative)

My testing environment was Linux (with Consumption Plan) + Python 3.10.4

Upvotes: 0

user459872
user459872

Reputation: 24562

You have already imported the module using

from . import test

so in order to access the function from the module you should use

num = test.sum_num(2, 3)

Alternatively you can import only the function from the module.

from .test import sum_num

Upvotes: 4

Related Questions