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!

有帮助吗?

解决方案

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:

  1. 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 .py file.

  2. The name got typo'd somehow. Maybe the filename, maybe the extension. For example, db.oy.

  3. You have old .pyc files. While I was testing this I deleted db.py, but it still worked because I still had the .pyc files in the directory. It was only after I deleted them that the error occurred.

其他提示

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!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top