SQLAlchemy Flask 错误:“当前 Flask 应用程序未在此‘SQLAlchemy’实例中注册”

问题描述 投票:0回答:1

由于(我认为)循环依赖,我遇到了问题。我返回的错误消息是:

“错误 - 获取和分析新闻时出错:当前 Flask 应用程序未在此“SQLAlchemy”实例中注册。您是否忘记调用“init_app”,或者是否创建了多个“SQLAlchemy”实例?”

我的应用程序.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()

我的新闻.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}")

有关更多信息,代码失败的行是:“

user = User.query.get(username)
”。

我相信 app.py 和 news.py 之间的循环依赖导致了这个问题,但我不确定如何解决它。我尝试过移动代码,但问题仍然存在。有人可以帮我找出这个问题的原因并提供解决方案吗?

预先感谢您的协助。

python flask sqlalchemy flask-sqlalchemy circular-dependency
1个回答
0
投票

在使用它之前,您需要调用

init_app()
来创建与数据库的连接。

在你的

app.py

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

# Database for user login
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy()
db.init_app(app) // init connection to db
# 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()

您还可以在使用之前检查数据库是否存在

db.create_all()

© www.soinside.com 2019 - 2024. All rights reserved.