Reputation: 681
I am wanting to import a class from my __init__
file. But I am unsuccessful in importing it. This is my directory structure
/fitBody_app
/fitBody
/static
/templates
__init__.py
models.py
views.py
run.py
These are all the imports of my __init__.py
file:
import os
from flask import Flask
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from wtforms import fields, widgets
from fitBody.views import my_app
from flask_bootstrap import Bootstrap
app = Flask(__name__)
db = SQLAlchemy(app)
These are all my imports in my views.py
file:
import bcrypt
from flask import flash, redirect, render_template, request, session, Blueprint, url_for
from fitBody.models import RegistrationForm
from fitBody.models import cursor, conn
from fitBody import db
my_app = Blueprint('fitBody', __name__)
<......>
When I try to run the file, this is my traceback:
Traceback (most recent call last):
File "/Users/kai/github-projects/fitBody_app/run.py", line 1, in <module>
from fitBody import app
File "/Users/kai/github-projects/fitBody_app/fitBody/__init__.py", line 9, in <module>
from fitBody.views import fitBody
File "/Users/kai/github-projects/fitBody_app/fitBody/views.py", line 8, in <module>
from fitBody import db
ImportError: cannot import name 'db'
I had thought that since I am importing from within the same folder that it is possible to just give the import like this.
How would I go about importing the db
object from the __init__.py
file?
Upvotes: 0
Views: 8615
Reputation: 4302
Since views.py use db
the import statement should come after db defination. Or for better design move blueprints to another file, and just keep blueprint's in that file:
#__init__.py
app = Flask(__name__)
db = SQLAlchemy(app)
from fitBody.views import my_app
Upvotes: 3
Reputation: 175
It doesn't have anything to do with importing from an __init__.py
file. Your views.py
is importing from your __init__.py
file, and __init__.py
file is importing from your views.py
, which is an import cycle. I am not sure how your models.py
looks like, but how about you initialize db
in models.py
and have both __init__.py
and views.py
import from models.py
Upvotes: 1