ModuleNotFoundError Cannot import from app.__init__.py - python

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

Related

Imports in Python using Flask

I keep getting this error when trying to import my app and app.models.
Traceback (most recent call last):
File "tools.py", line 3, in
from app import db
ModuleNotFoundError: No module named 'app'
app/
api/
__init__.py
users.py
...
db_tools/
__init__.py
tools.py
errors/
__init__.py
...
__init__.py
models.py
app/db_tools/tools.py file:
import psycopg2
import os
from app import db
from app.models import UpdateLogs
...rest of code...
def request_update_log_comment():
return input('Enter a comment for the update:\n')
def create_update_log_comment():
comment = request_update_log_comment()
update_logs = UpdateLogs()
update_logs.save_log(comment)
db.session.commit()
if __name__ == '__main__':
create_update_log_comment()
/db_tools/init.py
from flask import Blueprint
bp = Blueprint('db_tools', __name__)
from app.db_tools import tools
I understand that there is no db.py file in app. However, all the other files in app/api and app/errors use this import without issue.
What gives? The app/db_tools folder is structured just like app/api and app/errors. Here's an example from api/users.py that works just fine. Notice that app/users.py is at the same file level as app/tools.py just in a different folder.
app/api/users.py
from flask import jsonify, request, url_for, abort
import ssl
import base64
import re
from app import db
from app.api import bp
from app.api.auth0 import AuthError, requires_auth
from app.api.errors import bad_request
from app.models import CustomNotes, SavedSets, ContactMessages
...rest of code...
app/init.py
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from config import Config
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
db = SQLAlchemy()
migrate = Migrate()
cors = CORS()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
migrate.init_app(app, db)
cors.init_app(app)
from app.api import bp as api_bp
app.register_blueprint(api_bp, url_prefix='/api')
from app.errors import bp as errors_bp
app.register_blueprint(errors_bp)
from app.db_tools import bp as db_tools_bp
app.register_blueprint(db_tools_bp)
if not app.debug and not app.testing:
if app.config['LOG_TO_STDOUT']:
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
app.logger.addHandler(stream_handler)
else:
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/website.log',
maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('Flask app startup')
return app
from app import models
You are trying to get db from the app package, but there is nothing called db.
so your folder structure should include db
app/
api/
__init__.py
...
db_tools/
__init__.py
tools.py
errors/
__init__.py
...
__init__.py
db.py <----------------------------
models.py
Now, if you want to get the object db created in app/__init__ (db = SQLAlchemy()) that is something different. For this, you will need to design the code in a different way.
Not sure what are you using in tool.py that required an object db so I cannot be more specific.
There is no db in app directory or in app\__init__.py so how can you import db from app? hence the error.

How to fix Flask Blueprint Error - No Module Found

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="")

Flask Application Circular Dependencies

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

Why I can't move import at top?

I am learning Flask. I found example with follow code
__init__.py:
from flask import Flask
app = Flask(__name__)
from app import views
view.py:
from app import app
#app.route('/')
def index():
return "hello world"
and run.py (on top level):
from app import app
app.run()
I can't understand why I can't move from app import views to the top. If I do so I am getting error:
> run.py
Traceback (most recent call last):
File "F:\app1\run.py", line 1, in <module>
from app import app
File "F:\app1\app\__init__.py", line 2, in <module>
from app import views
File "F:\app1\app\views.py", line 1, in <module>
from app import app
ImportError: cannot import name 'app'
Python is interpreted language. When it comes to one line it try to execute it. And that is why you cannot import views before defining app.
Working version of __init__.py
app = Flask(__name__)
from app import views # it will "execute: views.py"
# views.py - indenting for better understanding
from app import app # App is defined here and it can be imported
Not working version of __init__.py
from app import vies # it will execute vies.py"
# vies.py - indenting for better understanding
from app import app # Exception - app doesn't exist here
app = Flask(__name__)
You need to be really careful with python imports.
In run.py file line
from app import app
means "from package app (folder with __init__.py file, F:\app1\app in your case, import object app", and in __init__.py file line
app = Flask(__name__)
creates an application object. Main confusion caused by your application name - app - which coincides with application object name.
If you move line
from app import views
above
app = Flask(__name__)
from app import app in view.py will raise ImportError, because object app from app package not defined yet.

Trying to run the sql-alchemy tutorial steps. Can't import db from console (ImportError: cannot import name 'db')

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.

Categories