Home > Enterprise >  ModuleNotFound error only in Flask subfolders, not in root
ModuleNotFound error only in Flask subfolders, not in root

Time:11-02

I am having a very annoying problem with module imports within a Flask app.

This is my file structure:

root > app > views > tests

In the views folder, there is a file called data.py. I wish to import this into a file called test_data.py in tests:

from app.views import data

This gives a ModuleNotFound error, saying that app is not a module (I have added an __init__.py file, although I believe this is no longer needed in Python 3).

However, in the root (foo) folder, I have another file that is using exactly the same absolute import successfully:

from app.views import data

Can anybody help me out, please, with how I am able to import successfully into files other than the root folder?

CodePudding user response:

So, if your test_data.py is inside tests, and you wish to import data.py from views folder, you need to tell python to look into the folder specifically. You can do this in your test_data.py using this:

import sys
sys.path.insert(1, '/root/app/views')

import data

remember that the path is the absolute path. If you are on windows, this would start from C:/ or something and on linux from root. Do not use the relative path but only absolute.

Hope this helps!

  • Related