Skip to main content

Flask-Celery-Tools

This is a fork of Flask-Celery-Helper

Even though the Flask documentation says Celery extensions are
unnecessary now, I found that I still need an extension to properly use Celery in large Flask applications. Specifically
I need an init_app() method to initialize Celery after I instantiate it.

This extension also comes with a single_instance method.

  • Python PyPy, 3.11, 3.12, 3.13 and 3.14 supported.
  • Celery 5.x is supported (>=5.3.6,<6). Compatibility CI tests the minimum version and the latest release allowed by that range with SQLite-backed tests.

Tests

Attribution

Single instance decorator inspired by Ryan Roemer.

Quickstart

Install:

pip install Flask-Celery-Tools  

Examples

Basic Example

# example.py  
from flask import Flask  
from flask_celery import Celery  

app = Flask('example')  
app.config['CELERY_BROKER_URL'] = 'redis://localhost'  
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost'  
app.config['CELERY_TASK_LOCK_BACKEND'] = 'redis://localhost'  
celery = Celery(app)  

@celery.task()  
def add_together(a: int, b: int) -> int:  
    return a + b  

if __name__ == '__main__':  
    result = add_together.delay(23, 42)  
    print(result.get())  

Run these two commands in separate terminals:

celery -A example.celery worker
python example.py

Factory Example

# extensions.py
from flask_celery import Celery

celery = Celery()
# application.py
from flask import Flask
from extensions import celery

def create_app() -> Flask:
    app = Flask(__name__)
    app.config['CELERY_IMPORTS'] = ('tasks.add_together', )
    app.config['CELERY_BROKER_URL'] = 'redis://localhost'
    app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost'
    app.config['CELERY_TASK_LOCK_BACKEND'] = 'redis://localhost'
    celery.init_app(app)
    return app
# tasks.py
from extensions import celery

@celery.task()
def add_together(a: int, b: int) -> int:
    return a + b
# manage.py
from application import create_app

app = create_app()
app.run()

Custom Task Base Class

You can provide your own base task class to Celery() or init_app(). It must extend celery.Task and will be used as the base for the internal FlaskTask, so Flask context injection is preserved while your custom behaviour (retry logic, logging, etc.) is inherited by all tasks.

# example.py
from celery import Task
from flask import Flask
from flask_celery import Celery

class MyBaseTask(Task):
    abstract = True

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print(f"Task {task_id} failed: {exc}")

app = Flask('example')
app.config['CELERY_BROKER_URL'] = 'redis://localhost'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost'
celery = Celery(app, task_cls=MyBaseTask)

@celery.task()
def add_together(a: int, b: int) -> int:
    return a + b

The same parameter is available on init_app() for the factory pattern. A value passed to init_app() takes precedence over one passed to Celery().

celery = Celery(task_cls=FallbackTask)
celery.init_app(app, task_cls=MyBaseTask)  # MyBaseTask wins

Single Instance Example

# example.py
import time
from flask import Flask
from flask_celery import Celery, single_instance
from flask_redis import Redis

app = Flask('example')
app.config['REDIS_URL'] = 'redis://localhost'
app.config['CELERY_BROKER_URL'] = 'redis://localhost'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost'
app.config['CELERY_TASK_LOCK_BACKEND'] = 'redis://localhost'
celery = Celery(app)
Redis(app)

@celery.task(bind=True)
@single_instance
def sleep_one_second(a: int, b: int) -> int:
    time.sleep(1)
    return a + b

if __name__ == '__main__':
    task1 = sleep_one_second.delay(23, 42)
    time.sleep(0.1)
    task2 = sleep_one_second.delay(20, 40)
    results1 = task1.get(propagate=False)
    results2 = task2.get(propagate=False)
    print(results1)  # 65
    if isinstance(results2, Exception) and str(results2) == 'Failed to acquire lock.':
        print('Another instance is already running.')
    else:
        print(results2)  # Should not happen.

Locking backends

Flask-Celery-Tools supports multiple locking backends you can use:

Filesystem

Filesystem locking backend is using file locks on filesystem where worker is running, WARNING this backend is not usable for distributed tasks!!!

Redis

Redis backend is using redis for storing task locks, this backend is good for distributed tasks.

Redis release is ownership-checked: a backend releases only a lease acquired in the current thread/process, using Redis's token comparison. Failed acquisitions do not grant release permission; an expired owner cannot remove a successor's lock. Nested acquisitions retain their individual tokens, and forked children discard inherited ownership state. reset_lock() follows the same ownership check for Redis rather than forcibly deleting another execution's lock.

By default, leases expire after the configured timeout and are not renewed. Ownership-safe cleanup alone does not keep a long-running operation exclusive after its lease expires.

Redis-backed tasks can opt into lease renewal:

app.config['CELERY_TASK_LOCK_BACKEND'] = (
    'redis://localhost/0?socket_timeout=2&socket_connect_timeout=2'
)

@celery.task(bind=True)
@single_instance(lock_timeout=30, include_args=True, renew_lock=True)
def long_running_task(task, record_id):
    ...

Renewal restores the captured owner's original TTL every third of the lease period. Redis socket timeouts must be finite and positive; a missing connect timeout inherits the read timeout. Choose timeouts shorter than the lease. Other backends reject renewal rather than silently running without it. The default remains renew_lock=False.

Cleanup signals the renewal thread to stop and waits up to five seconds. A healthy successful body receives a final ownership check before release. Loss detected by renewal checks, Redis renewal errors, or a heartbeat that cannot stop within five seconds cause LockLostError at context exit. An existing task exception is preserved and cleanup failures are logged. A process crash kills its heartbeat and leaves a finite expiring lease.

Renewal does not interrupt work already running when a lease is lost. Task effects may occur before the exit error is raised; this feature is not fencing or automatic cancellation. Applications that must reject expired owners' writes need resource-level exclusion/fencing and a cancellation/recovery policy.

Renewing task bodies can obtain a cooperative stop signal with from flask_celery import get_lock_lost_event. It returns the current acquisition's threading.Event, which the heartbeat sets when renewal is refused or fails. Check event.is_set() or pass the captured event to a cancellable operation. Do not set or clear this library-owned event. Outside a renewing single_instance body it returns None, including non-renewing tasks and application children forked from an active task. Nested calls restore the outer signal, and concurrent tasks have separate signals. Helper threads must receive the captured event explicitly; they do not inherit the task scope. LockManager.lock_lost_event provides the signal for direct context-manager users. Each acquisition gets a fresh event; a previous failure remains latched.

The signal reports detected renewal failure, not instantaneous expiry or a guarantee that the task still owns the resource while the event is unset. The application decides how to stop operations and records the resulting failure. Existing body exceptions still take precedence over LockLostError at exit. See redis-py's expiration and ownership documentation.

Redis ownership regressions start socket-only temporary redis-server instances when that executable is available. They never use a host Redis database:

BROKER=sqlite RESULT=sqlite LOCK=sqlite pytest tests/test_backend_redis.py

Database (MariaDB, PostgreSQL, etc)

Database backend is using database supported by SqlAlchemy to store task locks, this backend is good for distributed tasks. Except sqlite database that have same limitations as filesystem backend.

Metadata

Release files for Flask-Celery-Tools 1.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for Flask-Celery-Tools 1.10.0
File Size Uploaded Provenance Actions
flask_celery_tools-1.10.0.tar.gz 23.7 kB Without provenance Details for flask_celery_tools-1.10.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for Flask-Celery-Tools 1.10.0
File Interpreter ABI Platform Actions
flask_celery_tools-1.10.0-py3-none-any.whl Python 3 none any Details for flask_celery_tools-1.10.0-py3-none-any.whl

Total release size: 42.1 kB

Release files / flask_celery_tools-1.10.0.tar.gz

Download URL flask_celery_tools-1.10.0.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
f487f5e6ed40d0badc93d729bd96844239e501430d36978deb742dcd59e3d0d0
BLAKE2b-256 checksum
How to use checksums
0e6dc1ba86b1a5eb3638313e244991b11ff492a394f457d6edacd10f73f2778c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.5

Release files / flask_celery_tools-1.10.0-py3-none-any.whl

Download URL flask_celery_tools-1.10.0-py3-none-any.whl
Size 18.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9b95938c5dbe6b42bd2b79131f8c9257b3cbe4af5e851faf8ee69812c696b345
BLAKE2b-256 checksum
How to use checksums
6a275a7c1754412e44d3c317e30faea11e2ce853d1f6749d2cc5f6c7c2f6a1b9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.5

Security for Flask-Celery-Tools 1.10.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page