Introducción al framework Celery y a las colas de tareas asíncronas en Python.
Código fuente de los ejemplos disponible aquí:
https://github.com/albertoalcolea/charla-celery
15. Brokers soportados (v3.1)
Nombre Estado Monitorización Control remoto
RabbitMQ Estable Sí Sí
Redis Estable Sí Sí
MongoDB Experimental Sí Sí
Beanstalk Experimental No No
Amazon SQS Experimental No No
CouchDB Experimental No No
Zookeeper Experimental No No
Django ORM Experimental No No
SQLAlchemy Experimental No No
IronMQ Plugin de terceros No No
16.
17. Celery messaging at scale at Instagram
http://lc0.github.io/blog/2013/05/01/celery-messaging-
at-scale-at-instagram/
https://blogs.vmware.com/vfabric/2013/04/how-instag
ram-feeds-work-celery-and-rabbitmq.html
http://highscalability.com/blog/2012/4/9/the-instagram
-architecture-facebook-bought-for-a-cool-billio.html
18. Un poco de código
from celery import Celery
app = Celery('tasks', broker='amqp://')
@app.task
def add(x, y):
return x + y
19. Un poco de código
from celery import Celery
app = Celery('tasks', broker='redis://')
@app.task
def add(x, y):
return x + y
20. Un poco de código
from tasks import add
add.delay(4, 4)
21. Un poco de código
from celery import Celery
app = Celery('tasks', broker='amqp://', backend='redis://')
@app.task
def add(x, y):
return x + y
@app.task
def xsum(numbers):
return sum(numbers)
22. Un poco de código
from tasks import add
result = add.delay(4, 4)
results.ready() # True/False
results.get() # results.get(timeout=1)
result.traceback
23. Un poco de código
@app.task
def tarea_costosa(x, y):
try:
do_something()
except Exception, exc:
raise tarea_costosa.retry(exc=exc)
Si un nodo falla podemos reenviar la tarea a la cola.
25. Primitivas
Group
Lista de tareas que deben ser aplicadas en paralelo.
Chain
Tareas que se ejecutan una detrás de otra (callbacks).
from celery import group
res = group(add.s(i, i) for i in xrange(10))()
res.get(timeout=1)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
from celery import chain
res = chain(add.s(2, 2), add.s(4), add.s(8))()
res.get() # 16
(add.s(2, 2) | add.s(4) | add.s(8))().get()
26. Primitivas
Chord
Group con callback. Se ejecuta cuando todas terminan
Chunks
Divide lista de argumentos y ejecuta en paralelo
from celery import chord
res = chord((add.s(i, i) for i in xrange(10)), xsum.s())()
res.get() # 90
from celery import chunks
res = add.chunks(zip(range(100), range(100)), 10)()
res.get()
27. Primitivas
Chunks + Chord/Chain = map-reduce
@app.task
def map(x, y):
return x + y
@app.task
def reduce(numlist):
numbers = [item for sub in numlist for item in sub]
return sum(numbers)
>>> chain(add.chunks(items, 5).group(), reduce.s())().get()
9900
>>> chord(add.chunks(items, 2).group(), reduce.s())().get()
9900