Apscheduler在Flask中同时运行作业

2024-04-18 22:55:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在Flask中,我试图同时运行几个作业。但我面临着这个问题:

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.
Job "chron (trigger: interval[0:00:05], next run at: 2020-05-19 16:03:46 IST)" raised an exception
Traceback (most recent call last):
  File "C:\Users\mithi\AppData\Local\Programs\Python\Python37\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job
    retval = job.func(*job.args, **job.kwargs)
  File "c:\Users\mithi\Desktop\appengineering\server.py", line 128, in chron
    return jsonify({})
  File "C:\Users\mithi\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\json\__init__.py", line 358, in jsonify
    if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
  File "C:\Users\mithi\AppData\Local\Programs\Python\Python37\lib\site-packages\werkzeug\local.py", line 348, in __getattr__
    return getattr(self._get_current_object(), name)
  File "C:\Users\mithi\AppData\Local\Programs\Python\Python37\lib\site-packages\werkzeug\local.py", line 307, in _get_current_object
    return self.__local()
  File "C:\Users\mithi\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\globals.py", line 52, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

这是我的调度对象:

job_defaults = {
    'coalesce': False,
    'max_instances': 100
}

sched = BackgroundScheduler(daemon=True, job_defaults=job_defaults)
sched.start()

我通过定义以下函数来创建多个作业:

def etl():

    # read app config
    with open('appConfig.json', encoding="utf-8") as json_file:
        configData = json.load(json_file)

    for obj in configData:
        sched.add_job(chron, 'interval', seconds=5, args=[obj], id=obj)

基本上,该函数是通过调用函数“chron”来添加作业的,但是args和id是不同的,它们创建的作业是唯一的,每隔五秒钟运行一次。我在chron函数中得到应用程序上下文问题。我已经读过app_上下文,但仍然无法理解这个概念


Tags: inpyappliblocallinejobcurrent
1条回答
网友
1楼 · 发布于 2024-04-18 22:55:38

您的“chron”函数正在调用Flask current_app和jsonify(),但您似乎还没有推送Flask上下文,因此出现了此外部应用上下文运行时错误

在调用“contexted”func之前,需要推送Flask应用程序上下文

有两种方式,

app = Flask(__name__)
# do some stuff on your app if you need
app.app_context().push()
# do some other stuff

或者在你的时间函数中

with app.app_context():
    # do something

You can refer to manually pushing a context for more details

相关问题 更多 >