Home > OS >  Why can't I import my domain models into my flask app?
Why can't I import my domain models into my flask app?

Time:11-23

I've been working through the Architecture Patterns with Python book and am reworking my app to follow a folder structure like the one on the authors git repo for chapter 4: https://github.com/cosmicpython/code/tree/master/src/allocation

My problem is that I cannot get the flask_app.py to import any of the domain modules. I keep getting module not found error.

I have a folder structure like this:

src/
  peaked/
     domain/
       __init__.py 
       models.py
     api/
       __init__.py 
       flask_api.py        
     dataaccess/
       __init__.py 
       orm.py
       repository.py
  __init__.py   
  setup.py
  

The repository and orm modules can import import from the domain module just fine. using the standard from domain import models. The unit tests in a separate tests folder at the top level can also import domain and dataaccess classes and functions just fine.

However, as soon as I put the exact same import into the flask_api.py, I get a ModuleNotFound error saying 'no module named domain'.

I spent the last 6 hours going through flask docs, through the github repo and a couple of other blogs and I can't get it to work.

I'm currently lauching the flask app using python src/peaked/api/flask_api.py from the command line in VSCode. This works fine ( if I have just a simple flask file with no imports ). But as soon as I introduce one of the imports it breaks.

I can't seem to get flask run to work. I've tried using set FLASK_APP=src/peaked/api/flask_api.py but I just get a could not locate Flask application error.

The setup.py file simply contains:

from setuptools import setup

setup(
    name="peaked",
    version="0.1",
    packages=["peaked"],
)

Do I need to do something different to set up FLASK_APP when it is in a subdir? And why are the imports not working when they work just fine in other files?

CodePudding user response:

That's an awesome book, I hope you enjoy reading it as much as I did.

If I recall correctly, the package is installed before being used (check the docker files) and therefore are available globally. You could simulate this behavior adding your src/peaked folder to the PYTHONPATH environment variable (something like set PYTHONPATH=%PYTHONPATH%;C:\path_to\src\peaked) or you could add a line very start of flask_api.py file adding the src/peaked path in the sys.path variable:

import sys
sys.path.append('C:\\path_to\\src\\peaked')

Note that the last suggestion adds infrastructure complexity to your API (not desired).

  • Related