From f566d89ee566e50a04c22df1eebef0343e3cc1c0 Mon Sep 17 00:00:00 2001 From: Julian Edwards Date: Thu, 2 May 2024 14:35:16 +1000 Subject: [PATCH] Ensure flask context for job_failure handlers 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. --- spinach/contrib/flask_spinach.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/spinach/contrib/flask_spinach.py b/spinach/contrib/flask_spinach.py index 17857ef..be9bd99 100644 --- a/spinach/contrib/flask_spinach.py +++ b/spinach/contrib/flask_spinach.py @@ -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. @@ -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: