I have a directory setup as follows:
/directory
/directory/__init__.py
/directory/setup.py
/directory/app/db.py
/directory/app/__init__.py
The /directory/__init__.py file contains the line "import app" which then fails in /directory/app/__init__.py due to the line "import db" when I try to run the setup.py file.
HOWEVER, if I change the error line to "from app import db" then it works fine. Why is this? I'm guessing it has to do with the fact I run it from a parent directory. Is there any way to make this work? Or do I just change all of the imports to "from app import x" even when it's being called from the app folder?
Thanks for any clarification.
Edit: Here's the error:
Traceback (most recent call last):
File "setup.py", line 2, in <module>
import app
File "/directory/app/__init__.py", line 1, in <module>
import db
ImportError: No module named 'db'
Edit2: Here's the /directory/app/__init__.py file (/directory/__init__.py is empty)
import db
from flask import Flask, render_template
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
@app.route("/")
def hello():
return render_template()
def run(host, port):
db.init_db()
app.run(host=host, port=port)
Final Edit: I had rephrased my question here and was given the right answer. I wasn't sure if the python3 change was relevant. Thanks!
3 Answers 3
Like @sharth, I tried to copy your file structure and replicate your error, but with no success. The only way I could get it to fail was to delete db.py. So you need to make sure that you actually do have a db.py file in your app directory.
Some ways that it could escape your attention:
You have a
db.py.txt, or some other extension. It's possible your settings are such that file extensions are not automatically shown, so even though you think you are looking at a python file it is not actually a.pyfile.The name got typo'd somehow. Maybe the filename, maybe the extension. For example,
db.oy.You have old
.pycfiles. While I was testing this I deleteddb.py, but it still worked because I still had the.pycfiles in the directory. It was only after I deleted them that the error occurred.
2 Comments
*.pyc files and then test both from app import db and import app.The __init__.py files in a directory should be empty, because that files are "magic files".
So you must thinking about an redesign of importing your packages!
So, let your __init__.py files empty and then it should work!
Comments
If pip doesn't work, uninstall python. Reinstall it with advanced options and enable pip
__init__.pyfiles and at least the first two lines ofsetup.py?