0

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.

funie200
  • 3,688
  • 5
  • 21
  • 34
Paul Wilson
  • 562
  • 5
  • 16
  • the short answer: `\models\models.py` rename to `\some_other_name\models.py` – madzohan Nov 30 '20 at 11:25
  • also suggest to read about Flask application factory pattern and blueprints before thinking about app dir structure (search in github for ` flask create_app`) – madzohan Nov 30 '20 at 11:28
  • The stack trace show you are likely cyclic imports `models/xxx` require `app` also `app` require `models/xxx`, I believe the `ModuleNotFoundError` came from incorrect `PYTHONPATH`. – Praphan Klairith Nov 30 '20 at 11:45
  • Thank you @madzohan this was the correct answer. Worked perfectly and I've learnt not to name py files the same as directories. Please post as full answer and I will select thus so. – Paul Wilson Nov 30 '20 at 21:46

1 Answers1

0

The problem

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?

Solution #1


So you have to rename package or module name \models\models.py to make import system work properly.

Possible solution #2 (not sure)


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
madzohan
  • 11,488
  • 9
  • 40
  • 67
  • Thank you very much. I can confirm renaming `models/models.py` to `something_else/models.py` has fixed the issue. – Paul Wilson Dec 01 '20 at 19:19