RuntimeError:在请求上下文之外工作。烧瓶。多线程?

时间:2019-11-28 20:43:31

标签: python multithreading flask apscheduler

我检查了文档,得出的结论是,仅包装导致with app.test_request_context():中异常的代码即可解决我的问题。没有,with app.app_context():

也没有

我希望看到的是:每6秒调用一次tick()都无关紧要在我的应用程序的特定页面上-重定向到td_list(列出所有ToDO)和flash邮件。

请问有人可以模拟我的问题吗?

我在学习Flask中遵循自上而下的方法。我不了解多线程,这可能与我的问题有关(假设我运行Flask服务器并使用apscheduler,并在适当的时候尝试调用tick())。

  

工作“滴答声(触发:间隔[0:00:06],下次运行时间:2019-11-28 21:59:32 EET)”引发了异常

     

RuntimeError:在外部运行   请求上下文。

     

这通常意味着您尝试使用   需要一个有效的HTTP请求。查阅有关测试的文档   有关如何避免此问题的信息。

这在routes.py中:

@app.route("/tick", methods=['GET', 'POST'])
def tick():
   with app.app_context():
        flash("Something", 'info')
        return redirect(url_for('td_list'))




def Schedule_reminders():
    with app.test_request_context():
        if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
            # https://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode
            scheduler = BackgroundScheduler()

            scheduler.add_job(tick, 'interval', seconds=6)
            scheduler.start()

在创建Schedule_reminders()之后,我在__init__.py中呼叫app

app = Flask(__name__)
app.config['SECRET_KEY'] = '57916sdkfhsdfs0c676dsdsa80ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
bcrypt = Bcrypt(app)

from flaskblog import routes
routes.Schedule_reminders()

0 个答案:

没有答案
相关问题