| order | 2 |
|---|
Middlewares are super helpful. You can inject some code before or after task's execution.
Middlewares must implement taskiq.abc.middleware.TaskiqMiddleware abstract class.
Every method of a middleware can be either sync or async. Taskiq will execute it
as you expect.
For example:
::: tabs
@tab sync
@tab async
:::
Also, middlewares always have a reference to the current broker in self.broker field.
If you want to kick a message during the execution of some middleware hooks, you
may use self.broker to do so.
Taskiq-pipelines uses middlewares to call next tasks.
Worker hooks run after the message has been decoded and its task has been found. The diagram shows one execution, assuming that the middleware hooks themselves complete normally:
Worker middleware flow. Editable SVG. Edit diagram.
pre_executecan modify the message before the task runs.- Task execution and dependency cleanup produce the result. If an execution
error was found,
on_errorruns beforepost_execute. post_executeruns for both successful and failed task results.- A result containing
NoResultErrorskips result storage andpost_save. Other results, including ordinary task errors, are passed to the result backend. post_saveruns only after the backend saves the result successfully. A save error skipspost_save; it is logged, and can also be propagated by the receiver.
With multiple registered middlewares, pre_execute runs in registration order.
on_error, post_execute, and post_save run in reverse registration order.
These worker hooks are separate from the client-side pre_send and post_send
hooks. Exceptions raised by middleware hooks can interrupt this flow, so handle
them inside the middleware as described in the
architecture overview.
