SlideShare uma empresa Scribd logo
1 de 60
Baixar para ler offline
● 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():
# ...
Django React Celery Task Boilerplate

Mais conteúdo relacionado

Mais procurados

Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009tolmasky
 
Real world scala
Real world scalaReal world scala
Real world scalalunfu 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 overloadingRai University
 
優しい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 FornalQA 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 & ReactiveCocoaFlorent Pillet
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805t k
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For BeginnersWilson Su
 
Debugging JavaScript with Chrome
Debugging JavaScript with ChromeDebugging JavaScript with Chrome
Debugging JavaScript with ChromeIgor Zalutsky
 
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 boto3Luciano 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éesRomain Lecomte
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtupt 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 jsThomas 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 SwiftVincent 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 designjspha
 

Mais procurados (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
 

Semelhante a Django React Celery Task Boilerplate

Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-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 RelicGraham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 
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 copyBrian 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 copyBrian Aker
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API designmeij200
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopPeter Friese
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Getting Functional with Scala
Getting Functional with ScalaGetting Functional with Scala
Getting Functional with ScalaJorge 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 2015Michiel Borkent
 

Semelhante a Django React Celery Task Boilerplate (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
 

Mais de Filipe Ximenes

Multitenant applications: How and Why
Multitenant applications: How and WhyMultitenant applications: How and Why
Multitenant applications: How and WhyFilipe 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 pythonFilipe Ximenes
 
Boas práticas de django
Boas práticas de djangoBoas práticas de django
Boas práticas de djangoFilipe 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 HerokuFilipe Ximenes
 

Mais de 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
 

Último

Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Último (20)

Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Django React Celery Task Boilerplate

  • 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(): # ...