FLASK——RuntimeError: No application found

--- no python application found, check your startup logs for errors ---

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

 

!!请务必确认是否在app=create_app()之前调用了模型类。即使用了未定义变量app

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个错误通常是因为在 Flask 应用程序中访问了一个需要在主循环中运行的操作。这通常是因为 Flask 应用程序是在主线程中运行的,而一些操作需要在主循环中进行。 解决这个问题的方法是使用 Flask 提供的 `flask.cli.with_appcontext` 装饰器将需要在主循环中运行的操作包装起来,或者使用 Flask 的 `before_first_request` 装饰器在应用程序启动时执行一些操作。例如: ```python from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/submit', methods=['POST']) def submit(): data = request.form['data'] # 在这里访问需要在主循环中运行的操作会导致 RuntimeError return render_template('result.html', result=data) if __name__ == '__main__': app.run(debug=True) ``` 在上面的例子中,如果在 `submit` 函数中访问需要在主循环中运行的操作,比如访问数据库或者使用某个 GUI 工具包,就会导致 `RuntimeError: main thread is not in main loop` 错误。为了解决这个问题,我们可以使用 `flask.cli.with_appcontext` 装饰器将访问数据库的操作包装起来: ```python from flask import Flask, render_template, request from flask.cli import with_appcontext app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/submit', methods=['POST']) def submit(): data = request.form['data'] with app.app_context(): # 在这里访问数据库不会导致 RuntimeError result = db.query(data) return render_template('result.html', result=result) if __name__ == '__main__': app.run(debug=True) ``` 在这个例子中,我们使用了 `with app.app_context():` 将访问数据库的操作包装起来,这样就能够在 Flask 中安全地访问数据库了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值