SlideShare una empresa de Scribd logo
1 de 50
Descargar para leer sin conexión
Procrastinando com Celery



.




adriano petrich petrich@gmail.com #TDC2011
O que é o Celery?
Ponto forte do Celery
 • Gerenciador de tarefas assíncrono
Ponto forte do Celery
    • Gerenciador      de          tarefas
      assíncrono
    • Distribuído entre máquinas
Os dois pontos fortes
do Celery
    • Gerenciador      de          tarefas
      assíncrono
    • Distribuído entre máquinas
Os dois pontos fortes
do Celery
    • Gerenciador      de          tarefas
      assíncrono
    • Distribuído entre máquinas
    • Agendador
Celery
Dentre os pontos fortes do Celery
destacam-se

      • Gerenciador     de        tarefas
        assíncrono
      • Distribuído entre máquinas
      • Agendador
      • Com tolerância a falhas
Como Funciona?
Resposta Curta
.
Resposta Longa
Estrutura
Tarefa
Publicadores
Fila
Trabalhadores/Consumidores
Tarefa
Tarefa
from celery.task import task

@task
def foo(val):
    return val
Publicador
Publicadores
Sincronamente

 >>> foo(5)
 5
Publicadores
Assincronamente

 >>> res = foo.delay(5)
Dois Jeitos
# não bloqueia
>>> res.ready()
True ou False
>>> res.result
5
# ou bloqueia
>>> res.get()
5
Fila
Fila
Backend sugerido é o RabbitMQ
(todas as crianças legais do bairro usam
erlang)
Mas também suporta
Redis
Beanstalk
MongoDB
CouchDB
e bancos suportados pelo ORM do Django
Trabalhador
Trabalhador
Pode estar rodando em outra máquina
Cada Worker process ainda pode usar
vários threads
Trabalhador
$ celeryd

$ ./manage celeryd
Por que?
Web ou StandAlone?
Web
Painel de Escalabilidade (djangocon.eu)
http://2011.djangocon.eu/talks/47/
Problemas comuns
What are the common mistakes you see.
--------------------------------------
Things that take a long time ("sending an email")
that lock up a process. Using the filesystem for caching.
Testing locally and pushing it live and see it fall over.
Using an external API can also take a long time.
Work with timeouts to work around it.
Processos demorados
entopem os tubes
Soluções comuns
Tenha um celery de criança:
Scaling wise, what should you think about before scaling
becomes an actual issue? And what should you definitely
leave until the moment comes you need to scale?
----------------------------------------------

First things first: use a queue like   celery, even on small sites.
Get used to such a queue and have it   in place, that'll help a
lot with performance later.Make sure   you've got your database
schema is mostly OK. It doesn't have   to be perfect right away,
but at least mostly OK.

Expect something to change and assume you'll have to swap something
out later to improve the performance.
email.py
from celery.task import task
from django.core.mail import send_mail

@task
def send(subject, message, recipient_list,
                from_email=None, **kwargs):
    if subject[0] != "[":
        subject = "[projeto] "+ subject
    if from_email is None:
        from_email = "suporte@fuuuuuu.com"
    send_mail(subject, message, from_email,
                    recipient_list, **kwargs)
Um bom padrão
from email import send

@task
def relatorio(dados):
    ....gera relatorio....
    send.delay("Relatorio Pronto",
        """
        Pode baixadas daqui:
        http://fuuuuuu.com/relatorios/%s.pdf
        """% filename,
        (email,))
Stand
Alone
Scripts
Map Reduce
 tarefas = []
 livros =["iliada.txt","odisseia.txt"....]
 for filename in livros:
     tarefas.append(
         conta_palavras.delay(filename)
         )


para pegar o resultado
if all([i.ready() for i in tarefas]):
    palavras = sum([i.result for i in tarefas])
Armadilhas e dicas
Django-celery no
admin
Inicia um worker
$ ./manage.py celeryd -l info -E
e daí: BAM!
Tem que rolar também
$ ./manage.py celerycam
Testar
#no settings.py
TEST_RUNNER='djcelery.contrib.test_runner.run_tests'

from django.test import TestCase
from myapp.tasks import add

class AddTestCase(TestCase):

   def testNoError(self):
       """Test that the ``add`` task runs
       with no errors,
       and returns the correct result."""
       result = add.delay(8, 8)

        self.assertEquals(result.get(), 16)
        self.assertTrue(result.successful())
Sem resposta
CELERY_IGNORE_RESULT = True
Transactions no
django
def bar(request):
    sanduiche = Sanduiche("Pernil")
    sanduiche.save()
    avisa_novo.delay(sanduiche.id)
Especialmente se
MIDDLEWARE_CLASSES = (
    'django.middleware.transaction.TransactionMiddleware',
    ...
Assim
def bar(request):
    sanduiche = Sanduiche("Pernil")
    sanduiche.save()
    if transaction.is_managed():
        transaction.commit()
    avisa_novo.delay(sanduiche.id)
Para desenvolvimento
from socket import error

try:
    avisa_novo.delay(sanduiche.id)
except error:
    log.error("conexao recusada")
    if not DEBUG:
        raise error
Muitas tarefas
for i in algo_grande:
    avisa_novo.delay(i)
Muitas tarefas
subtasks = []
for i in algo_grande:
    subtasks.append(subtask(avisa_novo, args=(i)))

TaskSet(tasks=subtasks).apply_async()
Créditos
http://www.flickr.com/photos/lexnger/1794462309
http://www.flickr.com/photos/atmtx/4250159996
http://www.flickr.com/photos/prettydaisies/2368005479
http://www.flickr.com/photos/benobryan/3766107097
http://www.flickr.com/photos/eli_k_hayasaka/3989808211
http://www.flickr.com/photos/carolinabarmell/2980660350
http://www.flickr.com/photos/jjay/2415455625
http://www.flickr.com/photos/tim_proffitt_white/3181616233
http://www.flickr.com/photos/daniele_sartori/4484430735
http://www.flickr.com/photos/project-404/27730644
Dúvidas?
@fractal
+Adriano Petrich
[codando.com.br, sfp.adrianopetrich.com,
blog.adrianopetrich.com]
Deixa para depois, Procrastinando com Celery em Python

Más contenido relacionado

La actualidad más candente

Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 

La actualidad más candente (20)

AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Mozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver frameworkMozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver framework
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
Spock's New Tricks
Spock's New TricksSpock's New Tricks
Spock's New Tricks
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Testing Ansible
Testing AnsibleTesting Ansible
Testing Ansible
 
Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
 
Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Py.test
Py.testPy.test
Py.test
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript Applications
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 

Similar a Deixa para depois, Procrastinando com Celery em Python

Clojure in the Wild
Clojure in the WildClojure in the Wild
Clojure in the Wild
suitzero
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
Mauro Rocco
 

Similar a Deixa para depois, Procrastinando com Celery em Python (20)

Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
IaC and Immutable Infrastructure with Terraform, Сергей Марченко
IaC and Immutable Infrastructure with Terraform, Сергей МарченкоIaC and Immutable Infrastructure with Terraform, Сергей Марченко
IaC and Immutable Infrastructure with Terraform, Сергей Марченко
 
Celery
CeleryCelery
Celery
 
Django Celery
Django Celery Django Celery
Django Celery
 
Clojure in the Wild
Clojure in the WildClojure in the Wild
Clojure in the Wild
 
Building frameworks over Selenium
Building frameworks over SeleniumBuilding frameworks over Selenium
Building frameworks over Selenium
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Principles of the Play framework
Principles of the Play frameworkPrinciples of the Play framework
Principles of the Play framework
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
 
Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queue
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Deixa para depois, Procrastinando com Celery em Python