Integration with third-party libraries and frameworks.


Spinach uses the standard Python logging package. Its logger prefix is spinach. Spinach does nothing else besides creating its loggers and emitting log records. The user is responsible for configuring logging before starting workers.

For simple applications it is enough to use:

import logging

    format='%(asctime)s - %(threadName)s %(levelname)s: %(message)s',

More complex applications will probably use dictConfig.


The Flask integration follows the spirit of Flask very closely, it provides two ways of getting started: a single module approach for minial applications and an application factory approach for more scalable code.

The Spinach extension for Flask pushes an application context for the duration of the tasks, which means that it plays well with other extensions like Flask-SQLAlchemy and doesn’t require extra precautions.

Single Module

from flask import Flask
from spinach.contrib.flask_spinach import Spinach

app = Flask(__name__)
spinach = Spinach(app)

def say_hello():
    print('Hello from a task')

def home():
    return 'Hello from HTTP'

Application Factory

This more complex layout includes an Application Factory create_app and an imaginary auth Blueprint containing routes and tasks.

from flask import Flask
from spinach import RedisBroker
from spinach.contrib.flask_spinach import Spinach

spinach = Spinach()

def create_app():
    app = Flask(__name__)
    app.config['SPINACH_BROKER'] = RedisBroker()

    from . import auth
    spinach.register_tasks(app, auth.tasks)

    return app

from flask import Blueprint, jsonify
from spinach import Tasks

from .app import spinach

blueprint = Blueprint('auth', __name__)
tasks = Tasks()

def create_user():
    return jsonify({'user_id': 42})

def send_welcome_email():
    print('Sending email...')

Running workers

Workers can be launched from the Flask CLI:

$ FLASK_APP=examples.flaskapp flask spinach

The working queue and the number of threads can be changed with:

$ FLASK_APP=examples.flaskapp flask spinach --queue high-priority --threads 20


When in development mode, Flask uses its reloader to automatically restart the process when the code changes. When having periodic tasks defined, using the MemoryBroker and Flask reloader users may see their periodic tasks scheduled each time the code changes. If this is a problem, users are encouraged to switch to the RedisBroker for development.


  • SPINACH_BROKER, default spinach.RedisBroker()
  • SPINACH_NAMESPACE, defaults to the Flask app name


A Django application is available for integrating Spinach into Django projects.

To get started, add the application spinach.contrib.spinachd to


On startup, Spinach will look for a module in all installed applications. For instance polls/

from spinach import Tasks

from .models import Question

tasks = Tasks()

def close_poll(question_id: int):

Tasks can be easily scheduled from views:

from .models import Question
from .tasks import tasks

def close_poll_view(request, question_id):
    question = get_object_or_404(Question, pk=question_id)

Users of the Django Datadog app get their jobs reported to Datadog APM automatically in task workers.

Running workers

Workers can be launched from

$ python spinach

The working queue and the number of threads can be changed with:

$ python spinach --queue high-priority --threads 20

Sending emails in the background

The Spinach app provides an EMAIL_BACKEND allowing to send emails as background tasks. To use it simply add it to

EMAIL_BACKEND = 'spinach.contrib.spinachd.mail.BackgroundEmailBackend'
SPINACH_ACTUAL_EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

Emails can then be sent using regular Django functions:

from django.core.mail import send_mail

send_mail('Subject', 'Content', '', [''])

Periodically clearing expired sessions

Projects using django.contrib.sessions must remove expired session from the database from time to time. Django comes with a management command to do that manually, but this can be automated.

Spinach provides a periodic task, disabled by default, to do that. To enable it give it a periodicity in For instance to clear sessions once per week:

from datetime import timedelta



  • SPINACH_BROKER, default spinach.RedisBroker()
  • SPINACH_NAMESPACE, default spinach
  • SPINACH_ACTUAL_EMAIL_BACKEND, default django.core.mail.backends.smtp.EmailBackend


With the Sentry integration, failing jobs can be automatically reported to Sentry with full traceback, log breadcrumbs and job information.

The Sentry integration requires Sentry SDK:

pip install sentry_sdk

It then just needs to be registered before starting workers:

import sentry_sdk

from spinach.contrib.sentry_sdk_spinach import SpinachIntegration



Users of the deprecated Raven client for Sentry can use the old Spinach integration below.

The old integration requires Raven:

pip install raven

It then just needs to be registered before starting workers:

from raven import Client
from spinach.contrib.sentry import register_sentry

raven_client = Client('https://sentry_dsn/42')

spin = Engine(MemoryBroker())


With the Datadog integration, all jobs are automatically reported to Datadog APM.

The integration requires ddtrace, the Datadog APM client for Python:

pip install ddtrace

The integration just needs to be registered before starting workers:

from spinach.contrib.datadog import register_datadog


spin = Engine(MemoryBroker())

This only installs the integration with Spinach, other libraries still need to be patched by ddtrace. It is recommended to run your application patched as explained in the ddtrace documentation.

spinach.contrib.datadog.register_datadog(tracer=None, namespace: Optional[str] = None, service: str = 'spinach')

Register the Datadog integration.

Exceptions making jobs fail are sent to Sentry.

  • tracer – optionally use a custom ddtrace Tracer instead of the global one.
  • namespace – optionally only register the Datadog integration for a particular Spinach Engine
  • service – Datadog service associated with the trace, defaults to spinach