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'
Here is my tools.py file
import psycopg2
import os
from app import db
from app.models import UpdateLogs
...rest of file...
app/
api/
__init__.py
...
db_tools/
__init__.py
tools.py
errors/
__init__.py
...
__init__.py
models.py
What gives? The /db_tools folder is structured just like app/api and app/errors.
/db_tools/init.py
from flask import Blueprint
bp = Blueprint('db_tools', __name__)
from app.db_tools import tools
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/kanjiremastered.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
CodePudding user response:
There is no db
in app
directory or in app\__init__.py
so how can you import db
from app
? hence the error.
CodePudding user response:
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.