I am developing a Flask application, and I am not sure why I am getting this error:
File "app.py", line 17, in <module>
from endpoints.users.resource import UserResource
File "{basedir}/endpoints/users/resource.py", line 4, in <module>
from .model import User
File "{basedir}/endpoints/users/model.py", line 1, in <module>
from app import db
File "{basedir}/app.py", line 17, in <module>
from endpoints.users.resource import UserResource
ImportError: cannot import name 'UserResource' from 'endpoints.users.resource' ({basedir}/endpoints/users/resource.py)
I believe it is due to a circular dependency, from looking at the error, but I can't figure out why, because I think that the order in which I am importing things in my code should have circumvented this issue:
app.py:
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
api = Api(app)
api.prefix = '/api'
from endpoints.users.resource import UserResource
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from app import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from .model import User
from app import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
In app.py, since I am importing from endpoints.users.resource after db is created, shouldn't that circumvent the circular dependency?
In addition, I can run this with flask run but when I try to use python app.py, then it gives me the above error. Why would these give different results?
So on from endpoints.users.resource import UserResource line python tries to import from app import db line to app.py which causes app reference to itself, which is not good at all.
One workaround to solve circual import errors in Flask is using init_app function which exists in most of Flask apps. So just create database file like this:
database.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app.py
from flask import Flask
from flask_restful import Api
from database import db
from endpoints.users.resource import UserResource
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
api = Api(app)
api.prefix = '/api'
api.add_resource(UserResource, '/users')
if __name__ == '__main__':
app.run(host="0.0.0.0")
endpoints/users/model.py:
from database import db
class User(db.Model):
# info about the class, requires db
endpoints/users/resource.py:
from flask_restful import Resource
from endpoints.users.model import User
from database import db
class UserResource(Resource):
def get(self, username=None):
# get request, requires db and User
Note that I rewrote your imports from related, so don't forget to add __init__.py files
Your structure will be like this:
.
├── app.py
└── database.py/
└── endpoints/
├── __init__.py
└── users/
├── __init__.py
├── model.py
└── resource.py
Related
I'm trying to setup a flask application which runs on Python 3.7.x. I've referenced many tutorials online but can't seem to resolve this ModuleNotFoundError and none of the stackoverflow questions are related.
Below is my project structure:
project/
app/
__init__.py
api.py
conf.py
models.py
schema.py
orders-mgmt.toml
requirements.txt
README.md
# app/__init__.py
from flask import Flask
from flask_restful import Api
from app.conf import load_from_toml
import logging
import os.path
if os.path.isfile('/opt/project/orders-mgmt.toml'):
config = load_from_toml('/opt/project/orders-mgmt.toml')
else:
config = load_from_toml()
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = config['mysql']['db_uri']
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
'pool_recycle': 3000,
'pool_pre_ping': True,
}
# app/api.py
from flask import jsonify
from flask_restful import Resource
from flask_sqlalchemy import SQLAlchemy
from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema
db = SQLAlchemy(app)
class TestGet(Resource):
def get(self):
return 'okay'
api.add_resource(TestGet, '/')
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=5000)
I'm getting the ModuleNotFoundError in app/api.py line from app import app, api, config when I run python app/api.py:
$ python app/api.py
Traceback (most recent call last):
File "app/api.py", line 4, in <module>
from app import app, api, config
ModuleNotFoundError: No module named 'app'
May I know what is the issue here with my flask application?
You have circular dependency issue
Your app will not work in such files structure
Remove logic from init module to another one OR you'll need to remove all absolute imports(imports for your own modules) and replace them with relative
for __init__ module
replace this line:
from app.conf import load_from_toml
with
from .conf import load_from_toml
for app module
replace these lines:
from app import app, api, config #ERROR here
from app.models import Request
from app.schema import RequestSchema
with
from . import app, api, config
from .models import Request
from .schema import RequestSchema
I've looked at help guides and so forth but I still cannot seem to get Flask Blueprints working.
Here is my structure
root /
config.py
|app/
| __init__.py
| user_auth/
| __init__.py
| app.py
| routes.py
In the app/init.py file, it is the following
from flask import Flask
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
from .user_auth.routes import user_auth
app.register_blueprint(user_auth, url_prefix="")
From the user_auth init.py file is
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
app.config['SECRET_KEY'] = 'trial'
from user_auth import routes, models
This is the user_auth/routes.py file
from user_auth import app, db
from flask_login import login_required
from user_auth.forms import RegistrationForm, LoginForm
from flask import request, render_template, flash, redirect, url_for, Blueprint
from werkzeug.urls import url_parse
from flask_login import logout_user
from flask_login import current_user, login_user
from user_auth.models import User
from flask import Blueprint
user_auth = Blueprint('user_auth', __name__)
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html', title='Welcome')
#app.route('/register', methods=["POST", "GET"])
def register():
... (Other paths)
I am running Windows and used the following command
set FLASK_APP=app
I then use
flask run
When I try to run, it says the following:
Error: While importing "app", an ImportError was raised:
Traceback (most recent call last):
File "...\python38-32\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "...\root\app\__init__.py", line 8, in <module>
from .user_auth.routes import user_auth
File "...\root\app\user_auth\__init__.py", line 16, in <module>
from user_auth import routes, models
ModuleNotFoundError: No module named 'user_auth'
Thank you in advance for the help.
For all files in app/user_auth/ like the init.py and routes.py that you mentionned up there, you nede either to access the package with
absolute import : from root.app.user_auth
relative import : from ..user_auth
Then i'd suggest to not use the same name for more than 1 think, here user_auth is both a package name, and the the variable name of you blueprint
Change like
# routes.py
user_auth_bp = Blueprint('user_auth', __name__)
# app/__init__.py
from .user_auth.routes import user_auth_bp
app.register_blueprint(user_auth_bp, url_prefix="")
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?
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
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
Trying to run the tutorial here: http://flask-sqlalchemy.pocoo.org/2.1/quickstart/ using my app
I have looked at the circular imports problem but I don't think that's it. I'm an absolute beginner to python and flask (and sqlalchemy). My app currently runs, but the database part doesn't
This is the current setup:
mysite
|- __init__.py
|- flask_app.py
|- models.py
|- views.py
init.py
from flask import Flask
app = Flask(__name__)
flask_app.py
from flask import Flask, request, url_for
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:// -- database uri --'
... app continues here
models.py
from app import app
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Foo(db.Model):
... model continues here
views.py
from app import app,models
... views continue here, still not using anything from models
when I run from mysite import db in the python console I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'db'
Declare your db object in __init__.py. The stuff that is declared in __init__.py defines what can be imported under mysite/.
See: What is __init__.py for?
Also consider moving to the application factory pattern.
For example in __init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['DEBUG'] = True
... more application config ...
db.init_app(app)
return app
Then in flask_app.py:
from mysite import create_app, db
app = create_app()
if __name__ == '__main__':
app.run()
I point this out because you instantiate the app object twice in the code you've shown. Which is definitely wrong.
I'm trying to scale up my first Flask app and am not understanding the structure needed to use a pymongo db in multiple modules. For example, here is my new structure:
run.py
app/
├── __init__.py
├── forms.py
├── static/
├── templates/
└── views/
├── __init__.py
├── bookmarklet.py
├── main.py
└── user.py
Prior to trying to scale this, I had this at the top of my single views.py file:
from flask.ext.pymongo import PyMongo
mongo = PyMongo(app)
with app.app_context():
mongo.db.user.ensure_index("email", unique=True)
The goal is to be able to use this mongo instance in all of the view modules as well as the forms.py module. I've tried these two things:
Put the above snippet in the app/__init__.py file, but can't seem to make it accessible to any other modules. I tried doing this: app.db = mongo.db (but it wasn't available downstream)
Put the above snippet into each module that needs it, but then I get the error that there are multiple mongo instances with the same prefix.
Where should this initialization go in order to make it accessible everywhere in the app?
EDIT
It sounds like I'm doing it right but there is something else going on. I'm posting my more complete code and error.
app/__init__.py
from flask import Flask
app = Flask(__name__)
from app.views import main
app.config.update(
DEBUG = True,
SECRET_KEY = "not telling",
WTF_CSRF_ENABLED = False,
)
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
from flask.ext.pymongo import PyMongo
mongo = PyMongo(app)
with app.app_context():
mongo.db.user.ensure_index("email", unique=True)
app/views/main.py
from app import app
from flask import render_template, redirect, request, flash, url_for
from flask.ext.jsonpify import jsonify
from app.forms import *
from app import *
print mongo
Error:
(venv)imac: me$ ./run.py
Traceback (most recent call last):
File "./run.py", line 4, in <module>
from app import app
File "/Users/me/Dropbox/development/test/app/__init__.py", line 4, in <module>
from app.views import main
File "/Users/me/Dropbox/development/test/app/views/main.py", line 9, in <module>
print mongo
NameError: name 'mongo' is not defined
Put that snippet in app/__init__.py. If you want to access it in forms.py, for instance, try:
...
from app import *
# then you can use mongo here
print mongo
...
If you want to access it in user.py, for instance, try the same code above.
Check if this works for you. If not, show me the error message and I will think about solution two.
SOLVED
The mistake in my __init__.py file was that I was importing my views to early. You have to do that at the end!
WRONG
from flask import Flask
app = Flask(__name__)
from app.views import main # <- TOO EARLY
app.config.update(
DEBUG = True,
SECRET_KEY = "not telling",
WTF_CSRF_ENABLED = False,
)
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
from flask.ext.pymongo import PyMongo
mongo = PyMongo(app)
with app.app_context():
mongo.db.user.ensure_index("email", unique=True)
RIGHT
from flask import Flask
from flask.ext.pymongo import PyMongo
app = Flask(__name__)
mongo = PyMongo(app)
with app.app_context():
mongo.db.user.ensure_index("email", unique=True)
app.config.update(
DEBUG = True,
SECRET_KEY = "not telling",
WTF_CSRF_ENABLED = False,
)
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
# AT THE BOTTOM!
from app.views import main