Skip to content

Commit

Permalink
Ensure flask context for job_failure handlers
Browse files Browse the repository at this point in the history
For the flask_spinach object, similarly to the existing job_started and
job_finished signal handlers, there's now also a job_failed handler that
subclasses can use. These handlers are in place to ensure that the app
context is pushed before the handlers are called.
  • Loading branch information
bigjools committed May 2, 2024
1 parent 634c8da commit f566d89
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions spinach/contrib/flask_spinach.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ def job_finished(*args, job=None, **kwargs):
# This means we didn't create the context. Ignore.
pass

@signals.job_failed.connect_via(namespace)
def job_failed(args, job=None, **kwargs):
if not flask.has_app_context():
ctx = app.app_context()
ctx.push()
flask.g.spinach_ctx = ctx
self.job_failed(job)

@classmethod
def job_started(cls, *args, job=None, **kwargs):
"""Callback for subclasses to receive job_started signals.
Expand All @@ -73,6 +81,18 @@ def job_finished(cls, *args, job=None, **kwargs):
"""
pass

@classmethod
def job_failed(cls, *args, job=None, **kwargs):
"""Callback for subclasses to receive job_failed signals.
There's no guarantee of ordering for Signal's callbacks,
so use this callback instead to make sure the app context
was pushed. If the signal is called as part of dead broker
detection, you will need to use this as normal signals may
not have been called with the app context pushed.
"""
pass

@property
def spin(self):
if self.app is not None:
Expand Down

0 comments on commit f566d89

Please sign in to comment.