I had a problem with a circular import, so I moved my blueprint import below my app definition. However, I'm still having an import error.
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 2217, in <module>
globals = debugger.run(setup['file'], None, None)
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1643, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/benjamin/Documents/Projects/website/server/app/app.py", line 15, in <module>
from views import site
File "/Users/benjamin/Documents/Projects/website/server/app/views.py", line 2, in <module>
from models import User
File "/Users/benjamin/Documents/Projects/website/server/app/models.py", line 3, in <module>
from database_setup import db
File "/Users/benjamin/Documents/Projects/website/server/app/database_setup.py", line 1, in <module>
from app import app
File "/Users/benjamin/Documents/Projects/website/server/app/app.py", line 15, in <module>
from views import site
ImportError: cannot import name site
If I move the blueprint import and registration to if __name__ == '__main__':
, the problem goes away, but I'm not sure if this is a good idea.
if __name__ == '__main__':
from views import site
app.register_blueprint(site)
app.run()
Is this the right way to solve the problem, or is there another solution?
original app.py
without __main__
"fix":
from flask import Flask
app = Flask(__name__)
from views import site
app.register_blueprint(site)
if __name__ == '__main__':
app.debug = True
app.run()
views.py
:
from flask import Blueprint, render_template
site = Blueprint('site', __name__, template_folder='templates', static_folder='static')
@site.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
database_setup.py
:
from app import app
from flask_mongoengine import MongoEngine
app.config['MONGODB_SETTINGS'] = {'db': 'mst_website'}
db = MongoEngine(app)
models.py
:
from database_setup import db
class User(db.Document):
# ...
My file structure is:
/server
|-- requirements.txt
|-- env/ (virtual environment)
|-- app/ (my main app folder)
|-- static/
|-- templates/
|-- __init__.py
|-- app.py
|-- database_setup.py
|-- models.py
|-- views.py
See Question&Answers more detail:
os