ModuleNotFoundError running 'flask db migrate' after creating a shared models directory #554
Replies: 1 comment 1 reply
-
I don't really understand how you expect this to work. It looks like you have moved your models outside of the Flask application, so you have to tell Python where these models are so that the import works. In many cases you don't have to explicitly set If you don't want to explicitly set the import path, then run your app from the top level directory and then the import should work. |
Beta Was this translation helpful? Give feedback.
-
When I run a
flask db migrate
, I'm getting aModuleNotFoundError: No module named 'models' error
, that theapp/__init__.py
references.flask db migrate
worked previously with this app, but I recently consolidated my models into a single shared folder instead of having individualmodels.py
files for each app (api
andweb
) that were getting out of sync.I believe the issue has to do with setting the
PYTHONPATH
variable in some way before running the command, because when I run the app in PyCharm there are no issues. I've specified the shared models directory as a content root in PyCharm which also adds it automatically toPYTHONPATH
. I also have no issues running the app in a docker container where I setENV PYTHONPATH="/topleveldir"
in the Dockerfile.How can I set the
PYTHONPATH
correctly for'flask db migrate'
to work?Here's my project structure:
And the
ModuleNotFoundError
comes from how theregister_extensions(app)
function setup works, where it requires importing the User, Role objects. Specifically thefrom models import User, Role
line. Here's the general pattern (simplified) I followed for that:I have found that if I manually set
PYTHONPATH
to"/full/path/to/topleveldir"
before I run the'flask db migrate'
it does run without the module not found error, but I was hoping there is a way to automate this or config setting?Thank you!
Beta Was this translation helpful? Give feedback.
All reactions