Communitygithub.com

django-celery

Padrões de tarefas assíncronas com Django + Celery — configuração, design de tarefas, agendamento Beat, retentativas, workflows canvas, monitoramento e testes. Use ao adicionar jobs em background, tarefas agendadas ou processamento assíncrono a uma aplicação Django.

O que é django-celery?

Este skill fornece padrões de nível de produção para processamento de tarefas em background em aplicações Django usando Celery com Redis ou RabbitMQ. Ele cobre desde a configuração inicial do projeto (instalação, entrypoint celery.py, configurações do Django) até padrões avançados de design de tarefas, como tarefas básicas, com retentativa, idempotentes e com limite de tempo suave. Inclui também chamadas de tarefas (delay, apply_async), agendamento periódico via Beat (código ou banco de dados), workflows canvas (chain, group, chord), tratamento de erros com dead letter queue, testes unitários e de integração, e monitoramento com Flower. O skill é útil para qualquer desenvolvedor Django que precise adicionar jobs em background, tarefas agendadas ou processamento assíncrono, oferecendo boas práticas, listas de verificação de produção e identificação de anti-padrões. Ele suporta as plataformas Claude Code, Cursor e Codex, e é baseado na documentação SKILL.md que descreve detalhadamente cada aspecto do uso de Celery com Django.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/django-celery

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Padrões de Tarefas Assíncronas Django + Celery

Padrões de nível de produção para processamento de tarefas em background no Django usando Celery com Redis ou RabbitMQ.

Quando Ativar

  • Adicionar jobs em background ou processamento assíncrono a uma aplicação Django
  • Implementar tarefas periódicas/agendadas
  • Descarregar operações lentas (e-mail, geração de PDF, chamadas de API) do ciclo de requisição
  • Configurar o Celery Beat para agendamento estilo cron
  • Depurar falhas de tarefas, retentativas ou acúmulos na fila
  • Escrever testes para tarefas Celery

Configuração do Projeto

Instalação

pip install 'celery[redis]' django-celery-results django-celery-beat

celery.py — Ponto de Entrada do App

# config/celery.py
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.development')

app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()  # Descobre tasks.py em cada INSTALLED_APP

@app.task(bind=True, ignore_result=True)
def debug_task(self):
    print(f'Request: {self.request!r}')
# config/__init__.py
from .celery import app as celery_app

__all__ = ('celery_app',)

Configurações do Django

# config/settings/base.py

# Broker (Redis recomendado para produção)
CELERY_BROKER_URL = env('CELERY_BROKER_URL', default='redis://localhost:6379/0')
CELERY_RESULT_BACKEND = env('CELERY_RESULT_BACKEND', default='django-db')

# Serialização
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

# Comportamento da tarefa
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = 30 * 60        # Limite rígido: 30 min
CELERY_TASK_SOFT_TIME_LIMIT = 25 * 60   # Limite suave: envia SoftTimeLimitExceeded
CELERY_WORKER_PREFETCH_MULTIPLIER = 1   # Evita que o worker acumule tarefas longas
CELERY_TASK_ACKS_LATE = True            # Recoloca na fila se o worker cair

# Persistência de resultados
CELERY_RESULT_EXPIRES = 60 * 60 * 24   # Manter resultados por 24 horas

# Agendador Beat (para tarefas periódicas)
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'

# Apps instalados
INSTALLED_APPS += [
    'django_celery_results',
    'django_celery_beat',
]

Executando Workers

# Iniciar worker (desenvolvimento)
celery -A config worker --loglevel=info

# Iniciar agendador Beat (tarefas periódicas)
celery -A config beat --loglevel=info --scheduler django_celery_beat.schedulers:DatabaseScheduler

# Worker + Beat combinados (apenas dev, nunca produção)
celery -A config worker --beat --loglevel=info

# Produção: múltiplos workers com concorrência
celery -A config worker --loglevel=warning --concurrency=4 -Q default,high_priority

Padrões de Design de Tarefas

Tarefa Básica

# apps/notifications/tasks.py
from celery import shared_task
import logging

logger = logging.getLogger(__name__)

@shared_task(name='notifications.send_welcome_email')
def send_welcome_email(user_id: int) -> None:
    """Enviar e-mail de boas-vindas para usuário recém-registrado."""
    from apps.users.models import User
    from apps.notifications.services import EmailService

    try:
        user = User.objects.get(pk=user_id)
    except User.DoesNotExist:
        logger.warning('send_welcome_email: usuário %s não encontrado', user_id)
        return  # Idempotente — não levantar exceção, tarefa já impossível de completar

    EmailService.send_welcome(user)
    logger.info('E-mail de boas-vindas enviado para o usuário %s', user_id)

Tarefa com Retentativa

@shared_task(
    bind=True,
    name='integrations.sync_to_crm',
    max_retries=5,
    default_retry_delay=60,       # segundos antes da primeira retentativa
    autoretry_for=(ConnectionError, TimeoutError),
    retry_backoff=True,           # backoff exponencial
    retry_backoff_max=600,        # limite de 10 minutos
    retry_jitter=True,            # randomizar para evitar efeito manada
)
def sync_contact_to_crm(self, contact_id: int) -> dict:
    """Sincronizar contato com CRM externo com retentativa em falhas transitórias."""
    from apps.crm.services import CRMClient

    try:
        result = CRMClient().sync(contact_id)
        return result
    except CRMClient.RateLimitError as exc:
        # Atraso específico da retentativa a partir do cabeçalho da resposta
        raise self.retry(exc=exc, countdown=int(exc.retry_after))

Padrão de Tarefa Idempotente

Projete tarefas para que possam ser executadas com segurança várias vezes com as mesmas entradas:

@shared_task(name='orders.mark_shipped')
def mark_order_shipped(order_id: int, tracking_number: str) -> None:
    """Marcar pedido como enviado — seguro para executar múltiplas vezes."""
    from apps.orders.models import Order

    updated = Order.objects.filter(
        pk=order_id,
        status=Order.Status.PROCESSING,    # Proteção: atualizar apenas se ainda não enviado
    ).update(
        status=Order.Status.SHIPPED,
        tracking_number=tracking_number,
    )

    if not updated:
        logger.info('mark_order_shipped: pedido %s já enviado ou não encontrado', order_id)

Tarefa com Limite de Tempo Suave

from celery.exceptions import SoftTimeLimitExceeded

@shared_task(
    bind=True,
    name='reports.generate_pdf',
    soft_time_limit=120,
    time_limit=150,
)
def generate_pdf_report(self, report_id: int) -> str:
    """Gerar relatório PDF com tratamento gracioso de timeout."""
    from apps.reports.services import PDFGenerator

    try:
        path = PDFGenerator.build(report_id)
        return path
    except SoftTimeLimitExceeded:
        # Limpar arquivos parciais antes da interrupção forçada
        PDFGenerator.cleanup(report_id)
        raise

Chamando Tarefas

from datetime import timedelta
from django.utils import timezone

# Disparar e esquecer (assíncrono)
send_welcome_email.delay(user.pk)

# Agendar no futuro
send_reminder.apply_async(args=[user.pk], countdown=3600)  # 1 hora a partir de agora
send_reminder.apply_async(args=[user.pk], eta=timezone.now() + timedelta(days=1))

# Aplicar com roteamento de fila
sync_contact_to_crm.apply_async(args=[contact.pk], queue='high_priority')

# Executar sincronamente (testes / depuração apenas)
result = generate_pdf_report.apply(args=[report.pk])

Agendamento Beat (Tarefas Periódicas)

Agendamento Definido em Código

# config/settings/base.py
from celery.schedules import crontab

CELERY_BEAT_SCHEDULE = {
    'limpar-sessoes-expiradas': {
        'task': 'users.cleanup_expired_sessions',
        'schedule': crontab(hour=2, minute=0),   # 2h diariamente
    },
    'sincronizar-inventario': {
        'task': 'products.sync_inventory',
        'schedule': 60.0,                         # a cada 60 segundos
    },
    'resumo-semanal': {
        'task': 'notifications.send_weekly_digest',
        'schedule': crontab(day_of_week='monday', hour=8, minute=0),
    },
}

Agendamento Definido no Banco (via django-celery-beat)

# Gerenciar tarefas periódicas a partir do admin Django ou código
from django_celery_beat.models import PeriodicTask, CrontabSchedule
import json

schedule, _ = CrontabSchedule.objects.get_or_create(
    hour='*/6', minute='0',
    timezone='UTC',
)

PeriodicTask.objects.update_or_create(
    name='Sincronizar inventário a cada 6 horas',
    defaults={
        'crontab': schedule,
        'task': 'products.sync_inventory',
        'args': json.dumps([]),
        'enabled': True,
    }
)

Canvas: Encadeamento e Agrupamento de Tarefas

from celery import chain, group, chord

# Chain: executar tarefas sequencialmente, passando resultados
pipeline = chain(
    fetch_data.s(source_id),
    transform_data.s(),          # recebe o resultado de fetch_data como primeiro arg
    load_to_warehouse.s(),
)
pipeline.delay()

# Group: executar tarefas em paralelo
parallel = group(
    send_welcome_email.s(user_id)
    for user_id in new_user_ids
)
parallel.delay()

# Chord: tarefas paralelas + callback quando todas terminam
result = chord(
    group(process_chunk.s(chunk) for chunk in data_chunks),
    aggregate_results.s(),       # chamado com a lista de resultados dos chunks
)
result.delay()

Tratamento de Erros e Fila de Mensagens Mortas (Dead Letter Queue)

# apps/core/tasks.py
from celery.signals import task_failure

@task_failure.connect
def on_task_failure(sender, task_id, exception, args, kwargs, traceback, einfo, **kw):
    """Registrar todas as falhas de tarefas no Sentry / alertas."""
    import sentry_sdk
    with sentry_sdk.new_scope() as scope:
        scope.set_context('celery', {
            'task': sender.name,
            'task_id': task_id,
            'args': args,
            'kwargs': kwargs,
        })
        sentry_sdk.capture_exception(exception)
# Rotear tarefas com falha para a fila de mensagens mortas após retentativas máximas
@shared_task(
    bind=True,
    max_retries=3,
    name='payments.charge_card',
)
def charge_card(self, order_id: int) -> None:
    from apps.payments.models import Order, FailedCharge

    try:
        _do_charge(order_id)
    except Exception as exc:
        if self.request.retries >= self.max_retries:
            # Persistir na tabela de mensagens mortas para revisão manual
            FailedCharge.objects.create(
                order_id=order_id,
                error=str(exc),
                task_id=self.request.id,
            )
            return  # Não levantar — tarefa falhou permanentemente
        raise self.retry(exc=exc)

Testando Tarefas Celery

Teste Unitário (Sem Broker)

# tests/test_tasks.py
import pytest
from unittest.mock import patch, MagicMock
from apps.notifications.tasks import send_welcome_email

class TestSendWelcomeEmail:

    @pytest.mark.django_db
    def test_envia_email_para_usuario_existente(self, user):
        with patch('apps.notifications.services.EmailService') as mock_email:
            send_welcome_email(user.pk)
            mock_email.send_welcome.assert_called_once_with(user)

    @pytest.mark.django_db
    def test_ignora_usuario_ausente_graciosamente(self):
        """Não deve levantar exceção se o usuário for excluído entre o enfileiramento e a execução."""
        send_welcome_email(99999)  # Usuário inexistente — não deve levantar

Teste de Integração com CELERY_TASK_ALWAYS_EAGER

# config/settings/test.py
CELERY_TASK_ALWAYS_EAGER = True      # Executar tarefas sincronamente nos testes
CELERY_TASK_EAGER_PROPAGATES = True  # Relançar exceções das tarefas

# tests/test_integration.py
@pytest.mark.django_db
def test_registro_dispara_email_de_boas_vindas(client):
    with patch('apps.notifications.services.EmailService') as mock_email:
        response = client.post('/api/users/', {
            'email': '[email protected]',
            'password': 'senhaforte123',
        })

    assert response.status_code == 201
    mock_email.send_welcome.assert_called_once()

Testando Retentativas

@pytest.mark.django_db
def test_tarefa_retenta_em_erro_de_conexao():
    with patch('apps.crm.services.CRMClient.sync') as mock_sync:
        mock_sync.side_effect = ConnectionError('timeout')

        with pytest.raises(ConnectionError):
            sync_contact_to_crm.apply(args=[1], throw=True)

        assert mock_sync.call_count == 1  # Apenas primeira tentativa quando eager

Monitoramento

# Inspecionar workers e filas ativos
celery -A config inspect active
celery -A config inspect stats
celery -A config inspect reserved

# Verificar tamanhos das filas (Redis)
redis-cli llen celery

# Flower: monitor em tempo real baseado na web
pip install flower
celery -A config flower --port=5555

Anti-Padrões

# RUIM: Passar instâncias de modelo — podem estar obsoletas no momento da execução
send_welcome_email.delay(user)        # Nunca passar objetos ORM
send_welcome_email.delay(user.pk)     # Sempre passar PKs

# RUIM: Chamar tarefas sincronamente em views de produção
result = generate_report.apply()      # Bloqueia a thread da requisição

# RUIM: Tarefa não idempotente sem proteções
@shared_task
def charge_and_fulfill(order_id):
    order.charge()     # Pode cobrar duas vezes se a tarefa retentar!
    order.fulfill()

# BOM: Idempotente com proteção de status
@shared_task
def charge_and_fulfill(order_id):
    order = Order.objects.select_for_update().get(pk=order_id)
    if order.status != Order.Status.PENDING:
        return  # Já processado
    order.charge()
    order.fulfill()

Lista de Verificação de Produção

VerificaçãoConfiguração
Reinicialização do worker em caso de falhaUnidade supervisord ou systemd
CELERY_TASK_ACKS_LATE = TrueRecolocar tarefas na fila se o worker cair
CELERY_WORKER_PREFETCH_MULTIPLIER = 1Distribuição justa de tarefas longas
Filas separadas por prioridade-Q default,high_priority,low_priority
CELERY_TASK_SOFT_TIME_LIMIT definidoTimeout gracioso antes da interrupção forçada
Integração com SentryCapturar todos os sinais task_failure
Flower ou outro monitorVisibilidade sobre as profundidades das filas
Beat executado em apenas um nóEvitar execução duplicada de tarefas agendadas

Skills Relacionados

  • django-patterns — ORM, camada de serviço e estrutura do projeto
  • django-tdd — Testar modelos, views e serviços Django
  • python-testing — Configuração e fixtures do pytest

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Habilidades Relacionadas