Reputation: 349
In Flask I'm attempting to run several jobs concurrently. But I'm faced with this issue:
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.
Here is my schedular object:
job_defaults = {
'coalesce': False,
'max_instances': 100
}
sched = BackgroundScheduler(daemon=True, job_defaults=job_defaults)
sched.start()
I'm creating multiple jobs by defining the following function:
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)
Basically the function is adding jobs as a call to the function "chron" but args and id are different which creates unique jobs, running at intervals of five seconds. I get the app_context issue in the chron function. I have read about app_context but still unable to grasp the concept.
Upvotes: 0
Views: 1079
Reputation: 111
Your "chron" function is calling Flask current_app and jsonify() but it seems you haven't pushed a Flask context yet thus having this outside app context runtime error.
Before you can call a "contexted" func, you need to push your Flask app context.
Two ways of doing so,
app = Flask(__name__)
# do some stuff on your app if you need
app.app_context().push()
# do some other stuff
or in your chron func,
with app.app_context():
# do something
You can refer to manually pushing a context for more details
Upvotes: 1