I feel I'm making a rookie error that I can't pin down.
I have the following folder structure
--MyAppRoot\
--app.py
----\models\__init__.py
----\models\models.py
----\models\data_handler.py
----\models\forms.py
----\models\a_few_other_py_files_etc.py
Where my app.py has the usual Flask(__name__)
etc and db = SQLAlchemy(app)
initialised. Everything works fine, all the imports from the various models py files work fine, usual stuff such as flask forms, wtforms etc.
Inside my data_handler.py file I am running a scraper which utilises Pandas to .send_to_sql
however I now need to import db so I can execute a raw SQL query
in db.session.execute(query)
for a use in a Class but when doing so I get the following error:
Traceback (most recent call last):
File "C:/Users/me/PythonProjects/MyAppRoot/models/data_handler.py", line 7, in <module>
from app import db
File "C:\Users\me\PythonProjects\MyAppRoot\app.py", line 1, in <module>
from models.forms import (RegisterForm,
ModuleNotFoundError: No module named 'models.forms'; 'models' is not a package
Any help appreciated.
While running data_handler.py
python import system finds module named models
on the same directory level (models.py
). It doesn't look further through PYTHONPATH if name have matched.
The directory containing the script being run is placed at the beginning of the search path https://docs.python.org/3/tutorial/modules.html#the-module-search-path
How python deals with module and package having the same name?
So you have to rename package or module name \models\models.py
to make import system work properly.
You can try to run your script from C:/Users/me/PythonProjects/MyAppRoot/
dir rather than from C:/Users/me/PythonProjects/MyAppRoot/models/
in this way:
python -m models.data_handler
Thank you very much. I can confirm renaming
models/models.py
tosomething_else/models.py
has fixed the issue.