Skip to content
Advertisement

How to structure azure functions python project

I’m messing around with Azure Functions with Python and running into issues with getting a proper project directory structure. My goal is to have a library directory that I can put all the business logic in and then reference that from the functions entry point and also have a test directory that can test the functions and the library code directly. I have the following structure currently:

__app__
 | - MyFirstFunction
 | | - __init__.py
 | | - function.json
 | - library
 | | - __init__.py
 | | - services
 | | | - __init__.py
 | | | - sample_service.py
 | - host.json
 | - requirements.txt
 | - __init__.py
 | - tests
 | | - __init__.py
 | | - test_first_function.py

I ended up with this structure and am able to reference sample_service from the azure function using from __app__.library.services import sample_service and things seem to work, but I am unable to get the unit test to be able to properly reference the azure function. I have tried from ..HttpTrigger import main and from __app__.HttpTrigger import main in the test, but visual studio code is unable to discover the test when either of those imports statements are in place. I get the following errors respectively when I execute the test_first_function.py file directly: ImportError: attempted relative import with no known parent package and ModuleNotFoundError: No module named '__app__'

I’m far from an expert when it comes to Python modules and packages so any insight in how to fix these issues would be helpful. It would be good to get other ideas on how anyone else structures their Python azure functions projects

Advertisement

Answer

If you move your tests directory one level up, outside the __app__ directory, you should be able to, then, run the tests and import using from __app__.MyFirstFunction import myfunction

There is a discussion going on for improving the testing experience and the proper guidance (discussion) (work-item).

Meanwhile, the above suggestion should work fine. You could use this project (azure-functions branch) as a reference (linked by Brett Canon in the discussion tagged above).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement