SlideShare a Scribd company logo
● Xima (Filipe Ximenes)
○ Recife
○ 5 anos na comunidade
Python
○ Django
○ Javascript
○ APIs
○ Vinta
Django React boilerplate
https://github.com/vintasoftware/django-react-boilerplate
Django Role Permissions
https://github.com/vintasoftware/django-role-permissions
Tapioca
https://github.com/vintasoftware/tapioca-wrapper
●
●
●
●
●
?
from celery import Celery
app = Celery(...)
@app.task
def soma(a, b):
return a + b
resultado = soma.delay(4, 5).get()
print(resultado) # 9
@app.task
def atualizar_participantes(id_evento, n):
e = Eventos.objects.get(id=id_evento)
e.numero_de_participantes = n
e.save()
e = Eventos.objects.get(nome='PySE')
atualizar_participantes.delay(e.id, 9001)
resultado = soma.delay(4, 5).get()
?
@app.task
def soma(a, b):
return a + b
@app.task
def soma_todos(*args):
resultado = 0
for i in args:
resultado = soma.delay(resultado, i).get()
return resultado
soma_todos.delay(1, 2, 3, 4)
soma.apply_async(args=None, kwargs=None,
countdown=0, eta=None,
expires=None, **options)
r = soma.apply_async((1, 2), link=soma.s(3))
r.get() # 3
r.children[0].result # 6
from celery import chain
c = chain(soma.s(1, 2), soma.s(3), soma.s(4), soma.s(5))
r = c().get() # 15
=
c = soma.s(1, 2) | soma.s(3) | soma.s(4) | soma.s(5)
r = c().get() # 15
from celery.schedules import crontab
app.conf.beat_schedule = {
'soma-segunda-de-manhã': {
'task': 'tasks.soma',
'schedule': crontab(hour=7, minute=30,
day_of_week=1),
'args': (1, 2),
},
}
GET /eventos/12/ POST /eventos/
{
"nome": "Python Sudeste"
}
DELETE /eventos/12/PUT /eventos/12/
{
"nome": "Python Sudeste"
}
GET /eventos/12/ POST /eventos/
{
"nome": "Python Sudeste"
}
DELETE /eventos/12/PUT /eventos/12/
{
"nome": "Python Sudeste"
}
@app.task
def atualiza_dados():
user.status = 'atualizado'
user.save()
r = requisição_pro_facebook()
user.name = r.name
user.save()
@app.task
def newsletter_mensal():
r = requisição_pro_facebook()
if r.status != 200:
return
user.name = r.name
user.status = 'atualizado'
user.save()
vs.
@app.task
def newsletter_mensal():
usuarios = todos_os_usuarios()
for u in usuarios:
send(email, 'newsletter')
@app.task
def enviar_newsletter(email):
send(email, 'newsletter')
@app.task
def newsletter_mensal():
usuarios = todos_os_usuarios()
for u in usuarios:
enviar_newsletter.delay(u.email)
vs.
from tapioca.exceptions import TapiocaException
from tapioca_facebook import Facebook
@app.task(bind=True, retry_limit=4
default_retry_delay=2)
def likes_do_facebook(self):
api = Facebook(access_token=ACCESS_TOKEN)
try:
api.user_likes(id='me').get()
except TapiocaException as e:
self.retry(exc=e)
def backoff_exponencial(task_self):
minutos = task_self.default_retry_delay / 60
rand = random.uniform(minutos, minutos * 1.3)
return int(rand ** task_self.request.retries) * 60
self.retry(exc=e,
countdown=backoff_exponencial(self))
from celery.exceptions import SoftTimeLimitExceeded
@app.task(task_soft_time_limit=30)
def mytask():
try:
tarefa_possivelmente_longa()
except SoftTimeLimitExceeded:
recuperar()
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
@app.task
def soma(a, b):
logger.info('Soma {0} + {1}'.format(a, b))
return a + b
class Task(object):
# ...
def apply_assync():
# ...
if app.conf.task_always_eager:
return self.apply(...)
# ...
# ...
from celery.contrib import rdb
@app.task
def soma_debug(a, b):
rdb.set_trace()
return a + b
Licenças:
http://www.flaticon.com/authors/madebyoliver
app.conf.task_routes = {
'app.tasks.somar': {'queue': 'somar'},
'app.tasks.subtrair': {'queue': 'subtrair'}
}
$ celery -A proj worker -Q somar, celery
$ celery -A proj worker -Q subtrair
somar.apply_async((1, 2), queue='subtrair')
from celery import signature
signature('tasks.add', args=(2, 2), countdown=10)
add.signature((2, 2), countdown=10)
add.s(2, 2)
add.s(2, 2)()
add.delay(2, 2)
add.signature((2, 2), countdown=1).apply_async()
partial = add.s(2)
partial.delay(4)
c = chain(add.s(4, 4), mul.s(8), mul.s(10))
res = c().get() # 640
g = group(add.s(2, 2), add.s(4, 4))
res = g().get() # [4, 8]
callback = tsum.s()
header = [add.s(i, i) for i in range(100)]
result = chord(header)(callback)
result.get() # 9900
x = xsum.map([range(10), range(100)]).delay()
x.get() # [45, 4950]
p = zip(range(10), range(10))
p # [(0, 0), (1, 1), (2, 2), ...]
s = add.starmap(p).delay()
s.get() # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
p2 = zip(range(100), range(100))
c = add.chunks(p2, 10)
c().get()
# [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
# [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
# ...
from celery import Task
class CustomTask(Task):
def after_return(self, status, retval, task_id,
args, kwargs, einfo):
# ...
def on_failure(self, exc, task_id, args, kwargs,
einfo):
# ...
def on_retry(self, exc, task_id, args, kwargs, einfo):
# ...
def on_success(self, retval, task_id, args, kwargs):
# ...
@app.task(base=CustomTask)
def my_task():
# ...
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas

More Related Content

What's hot

Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
tolmasky
 
Real world scala
Real world scalaReal world scala
Real world scala
lunfu zhong
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
Rai University
 
Flex With Rubyamf
Flex With RubyamfFlex With Rubyamf
Flex With Rubyamf
Tony Hillerson
 
Présentation de HomeKit
Présentation de HomeKitPrésentation de HomeKit
Présentation de HomeKit
CocoaHeads France
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方
techmemo
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert Fornal
QA or the Highway
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持
jeffz
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
t k
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
Wilson Su
 
Debugging JavaScript with Chrome
Debugging JavaScript with ChromeDebugging JavaScript with Chrome
Debugging JavaScript with Chrome
Igor Zalutsky
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
Luciano Mammino
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
Romain Lecomte
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtup
t k
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
Thomas Roch
 
Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?
Rafal Ksiazek
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles
 
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library designOf Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
jspha
 

What's hot (20)

Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
 
Real world scala
Real world scalaReal world scala
Real world scala
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
Flex With Rubyamf
Flex With RubyamfFlex With Rubyamf
Flex With Rubyamf
 
Présentation de HomeKit
Présentation de HomeKitPrésentation de HomeKit
Présentation de HomeKit
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert Fornal
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
 
Debugging JavaScript with Chrome
Debugging JavaScript with ChromeDebugging JavaScript with Chrome
Debugging JavaScript with Chrome
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtup
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?Why should we use SIMPLE FACTORY pattern even when we have one class only?
Why should we use SIMPLE FACTORY pattern even when we have one class only?
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library designOf Harmony and Stinginess: Applicative, Monad, and iterative library design
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
 

Similar to [Quase] Tudo que você precisa saber sobre tarefas assíncronas

Practical Celery
Practical CeleryPractical Celery
Practical Celery
Cameron Maske
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
ChengHui Weng
 
Next Level Testing Revisited
Next Level Testing RevisitedNext Level Testing Revisited
Next Level Testing Revisited
James Saryerwinnie
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
Adam Lowry
 
DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
Simone Federici
 
Fabric Python Lib
Fabric Python LibFabric Python Lib
Fabric Python Lib
Simone Federici
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
Graham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
New Relic
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
Django Celery
Django Celery Django Celery
Django Celery
Mat Clayton
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copy
Brian Aker
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copy
Brian Aker
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
Zaar Hai
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API design
meij200
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI Workshop
Peter Friese
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
dreampuf
 
Getting Functional with Scala
Getting Functional with ScalaGetting Functional with Scala
Getting Functional with Scala
Jorge Paez
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 

Similar to [Quase] Tudo que você precisa saber sobre tarefas assíncronas (20)

Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Next Level Testing Revisited
Next Level Testing RevisitedNext Level Testing Revisited
Next Level Testing Revisited
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
 
Fabric Python Lib
Fabric Python LibFabric Python Lib
Fabric Python Lib
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Django Celery
Django Celery Django Celery
Django Celery
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copy
 
Gearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copyGearmam, from the_worker's_perspective copy
Gearmam, from the_worker's_perspective copy
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API design
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI Workshop
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Getting Functional with Scala
Getting Functional with ScalaGetting Functional with Scala
Getting Functional with Scala
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 

More from Filipe Ximenes

Multitenant applications: How and Why
Multitenant applications: How and WhyMultitenant applications: How and Why
Multitenant applications: How and Why
Filipe Ximenes
 
O que é esse tal de rest? [PyBR2016]
O que é esse tal de rest? [PyBR2016]O que é esse tal de rest? [PyBR2016]
O que é esse tal de rest? [PyBR2016]
Filipe Ximenes
 
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
Filipe Ximenes
 
Usando tapioca para acessar APIs web [PyBR11]
Usando tapioca para acessar APIs web [PyBR11]Usando tapioca para acessar APIs web [PyBR11]
Usando tapioca para acessar APIs web [PyBR11]
Filipe Ximenes
 
Expressões idiomáticas do python
Expressões idiomáticas do pythonExpressões idiomáticas do python
Expressões idiomáticas do python
Filipe Ximenes
 
Boas práticas de django
Boas práticas de djangoBoas práticas de django
Boas práticas de django
Filipe Ximenes
 
Migrando do App Engine para o Heroku
Migrando do App Engine para o HerokuMigrando do App Engine para o Heroku
Migrando do App Engine para o Heroku
Filipe Ximenes
 

More from Filipe Ximenes (7)

Multitenant applications: How and Why
Multitenant applications: How and WhyMultitenant applications: How and Why
Multitenant applications: How and Why
 
O que é esse tal de rest? [PyBR2016]
O que é esse tal de rest? [PyBR2016]O que é esse tal de rest? [PyBR2016]
O que é esse tal de rest? [PyBR2016]
 
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
APIs: o que são? onde vivem? do que se alimentam? [PyNE2016]
 
Usando tapioca para acessar APIs web [PyBR11]
Usando tapioca para acessar APIs web [PyBR11]Usando tapioca para acessar APIs web [PyBR11]
Usando tapioca para acessar APIs web [PyBR11]
 
Expressões idiomáticas do python
Expressões idiomáticas do pythonExpressões idiomáticas do python
Expressões idiomáticas do python
 
Boas práticas de django
Boas práticas de djangoBoas práticas de django
Boas práticas de django
 
Migrando do App Engine para o Heroku
Migrando do App Engine para o HerokuMigrando do App Engine para o Heroku
Migrando do App Engine para o Heroku
 

Recently uploaded

原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 

Recently uploaded (20)

原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 

[Quase] Tudo que você precisa saber sobre tarefas assíncronas

  • 1.
  • 2. ● Xima (Filipe Ximenes) ○ Recife ○ 5 anos na comunidade Python ○ Django ○ Javascript ○ APIs ○ Vinta
  • 3.
  • 4. Django React boilerplate https://github.com/vintasoftware/django-react-boilerplate Django Role Permissions https://github.com/vintasoftware/django-role-permissions Tapioca https://github.com/vintasoftware/tapioca-wrapper
  • 5.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12. ?
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20. from celery import Celery app = Celery(...) @app.task def soma(a, b): return a + b resultado = soma.delay(4, 5).get() print(resultado) # 9
  • 21. @app.task def atualizar_participantes(id_evento, n): e = Eventos.objects.get(id=id_evento) e.numero_de_participantes = n e.save() e = Eventos.objects.get(nome='PySE') atualizar_participantes.delay(e.id, 9001)
  • 22.
  • 24.
  • 25. @app.task def soma(a, b): return a + b @app.task def soma_todos(*args): resultado = 0 for i in args: resultado = soma.delay(resultado, i).get() return resultado soma_todos.delay(1, 2, 3, 4)
  • 26.
  • 28. r = soma.apply_async((1, 2), link=soma.s(3)) r.get() # 3 r.children[0].result # 6
  • 29. from celery import chain c = chain(soma.s(1, 2), soma.s(3), soma.s(4), soma.s(5)) r = c().get() # 15 = c = soma.s(1, 2) | soma.s(3) | soma.s(4) | soma.s(5) r = c().get() # 15
  • 30. from celery.schedules import crontab app.conf.beat_schedule = { 'soma-segunda-de-manhã': { 'task': 'tasks.soma', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (1, 2), }, }
  • 31.
  • 32.
  • 33.
  • 34. GET /eventos/12/ POST /eventos/ { "nome": "Python Sudeste" } DELETE /eventos/12/PUT /eventos/12/ { "nome": "Python Sudeste" }
  • 35. GET /eventos/12/ POST /eventos/ { "nome": "Python Sudeste" } DELETE /eventos/12/PUT /eventos/12/ { "nome": "Python Sudeste" }
  • 36.
  • 37. @app.task def atualiza_dados(): user.status = 'atualizado' user.save() r = requisição_pro_facebook() user.name = r.name user.save() @app.task def newsletter_mensal(): r = requisição_pro_facebook() if r.status != 200: return user.name = r.name user.status = 'atualizado' user.save() vs.
  • 38. @app.task def newsletter_mensal(): usuarios = todos_os_usuarios() for u in usuarios: send(email, 'newsletter') @app.task def enviar_newsletter(email): send(email, 'newsletter') @app.task def newsletter_mensal(): usuarios = todos_os_usuarios() for u in usuarios: enviar_newsletter.delay(u.email) vs.
  • 39. from tapioca.exceptions import TapiocaException from tapioca_facebook import Facebook @app.task(bind=True, retry_limit=4 default_retry_delay=2) def likes_do_facebook(self): api = Facebook(access_token=ACCESS_TOKEN) try: api.user_likes(id='me').get() except TapiocaException as e: self.retry(exc=e)
  • 40. def backoff_exponencial(task_self): minutos = task_self.default_retry_delay / 60 rand = random.uniform(minutos, minutos * 1.3) return int(rand ** task_self.request.retries) * 60 self.retry(exc=e, countdown=backoff_exponencial(self))
  • 41. from celery.exceptions import SoftTimeLimitExceeded @app.task(task_soft_time_limit=30) def mytask(): try: tarefa_possivelmente_longa() except SoftTimeLimitExceeded: recuperar()
  • 42.
  • 43.
  • 44. from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @app.task def soma(a, b): logger.info('Soma {0} + {1}'.format(a, b)) return a + b
  • 45.
  • 46.
  • 47.
  • 48. class Task(object): # ... def apply_assync(): # ... if app.conf.task_always_eager: return self.apply(...) # ... # ...
  • 49. from celery.contrib import rdb @app.task def soma_debug(a, b): rdb.set_trace() return a + b
  • 50.
  • 52.
  • 53. app.conf.task_routes = { 'app.tasks.somar': {'queue': 'somar'}, 'app.tasks.subtrair': {'queue': 'subtrair'} } $ celery -A proj worker -Q somar, celery $ celery -A proj worker -Q subtrair somar.apply_async((1, 2), queue='subtrair')
  • 54.
  • 55. from celery import signature signature('tasks.add', args=(2, 2), countdown=10) add.signature((2, 2), countdown=10) add.s(2, 2) add.s(2, 2)() add.delay(2, 2) add.signature((2, 2), countdown=1).apply_async() partial = add.s(2) partial.delay(4)
  • 56. c = chain(add.s(4, 4), mul.s(8), mul.s(10)) res = c().get() # 640 g = group(add.s(2, 2), add.s(4, 4)) res = g().get() # [4, 8] callback = tsum.s() header = [add.s(i, i) for i in range(100)] result = chord(header)(callback) result.get() # 9900
  • 57. x = xsum.map([range(10), range(100)]).delay() x.get() # [45, 4950] p = zip(range(10), range(10)) p # [(0, 0), (1, 1), (2, 2), ...] s = add.starmap(p).delay() s.get() # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] p2 = zip(range(100), range(100)) c = add.chunks(p2, 10) c().get() # [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], # [20, 22, 24, 26, 28, 30, 32, 34, 36, 38], # ...
  • 58.
  • 59. from celery import Task class CustomTask(Task): def after_return(self, status, retval, task_id, args, kwargs, einfo): # ... def on_failure(self, exc, task_id, args, kwargs, einfo): # ... def on_retry(self, exc, task_id, args, kwargs, einfo): # ... def on_success(self, retval, task_id, args, kwargs): # ... @app.task(base=CustomTask) def my_task(): # ...