SQLAlchemy Flask Error: "The current Flask app is not registered with this 'SQLAlchemy' instance"

202 Views Asked by At

I am having an issue due to (I think) a circular dependency. The error message I am being returned is:

"ERROR - Error fetching and analyzing news: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?"

my app.py:

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

# Database for user login
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)

# Create user model
class User(db.Model):
    username = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
    password = db.Column(db.String(120), nullable=False)

    filter_keyword = db.Column(db.String(100))  # Change the length as needed

with app.app_context():
    db.create_all()

my news.py:

def get_news():
    from app import User
    rss_urls = [
        'https://feeds.bloomberg.com/markets/news.rss',
        'https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=10000664',
        'https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=10001054',
        'https://feeds.content.dowjones.io/public/rss/mw_topstories',
        'https://www.investing.com/rss/news_25.rss'
        # Add more RSS feed URLs as needed
    ]
    try:
        user = None
        filter_keyword = ''

        # Check if user is logged in and get their preference
        if 'username' in session:
            username = session['username']
            print(username)
            user = User.query.get(username)
            print("in,", user)


except Exception as e:
    logging.error(f"Error fetching and analyzing news: {e}")

For more information, the line that the code is failing on is: "user = User.query.get(username)".

I believe the circular dependency between app.py and news.py is causing this issue, but I'm not sure how to resolve it. I've tried moving code around, but the problem persists. Can someone help me identify the cause of this issue and provide a solution?

Thank you in advance for your assistance.

1

There are 1 best solutions below

1
TanThien On

You need call init_app() to create connection to DB before using it.

Create a extensions.py:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

create a model user.py

from extensions import db

class User(db.Model):
    username = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
    password = db.Column(db.String(120), nullable=False)
    filter_keyword = db.Column(db.String(100))  # Change the length as needed

In your app.py

from extensions import db
from flask import Flask

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db.init_app(app) // init connection to db


with app.app_context():
    db.create_all()

In your news.py:

from users import User

You also can check db exist before using db.create_all()