Import models across directories

Viewed 38
Backend
├── Flaskr
│   └── __init__.py
└── models.py

I want to import model.py into __init__.py

I tried from models import setup_db, Book I tried from backend.models import setup_db, Book

I end up up getting one of these two errors:

from models import setup_db, Book

ModuleNotFoundError: No module named 'models'

or

from backend.models import setup_db, Book

ModuleNotFoundError: No module named 'backend'

1 Answers

Here is something to try, not sure how it will work

First import sys in init.py

import sys

Second, add the path / directory of models.py

sys.path.insert(0, '/the/folder/path/name-package/')

Then, make another file called init.py, leave it blank. Leave it in the same directory as models.py. This is so python knows it is a package.

Lastly, import models.py from the backend folder

from backend import models

I am not sure if this will work but it may be worth a try if other peoples suggestions don't work very well.

Thanks for your time.

Edit: You may also be able to use this instead of using the exact path.

sys.path.insert("../")

this in theory will select the path of the backend by going back a directory.

Related