SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
Transakcyjność w Django
Marcin Baran @Sharpekk
internetowykantor.pl
Zagnieżdżone transakcje
W pewnej aplikacji w Django..
@transaction.commit_on_success
def run():
Counter.objects.update(views= 1)
foo()
bar()
@transaction.commit_on_success
def foo():
Counter.objects.update(views= 2)
@transaction.commit_on_success
def bar():
Counter.objects.update(views= 3)

BEGIN
UPDATE "bar_counter" SET "views" = 1
UPDATE "bar_counter" SET "views" = 2
COMMIT
BEGIN
UPDATE "bar_counter" SET "views" = 3
COMMIT
#HEHESZKA ;-)
BEGIN
UPDATE "bar_counter" SET "views" = 1
UPDATE "bar_counter" SET "views" = 2
COMMIT
BEGIN
UPDATE "bar_counter" SET "views" = 3
COMMIT
@commit_on_success_unless_managed
@commit_on_success_unless_managed
def run():
Counter.objects.update(views= 1)
foo()
bar()
@commit_on_success_unless_managed
def foo():
Counter.objects.update(views= 2)
@commit_on_success_unless_managed
def bar():
Counter.objects.update(views= 3)

BEGIN
UPDATE "bar_counter" SET "views" = 1
UPDATE "bar_counter" SET "views" = 2
UPDATE "bar_counter" SET "views" = 3
COMMIT
Race Condition
Counter.objects.update(views= 1)

# Watęk A (w tym samym czasie)

# Watęk B (w tym samym czasie)
counter = Counter.objects.get(pk= 1)

counter = Counter.objects.get(pk= 1)
counter.views += 1
counter.save()

print Couter.objects.get(pk= 1).counter
>>> 2

counter.views += 1
counter.save()
SELECT … FOR UPDATE
print Counter.objects.update(views= 1)

# Watęk A
counter = Counter.objects.
select_for_update().get(pk= 1)
time.sleep( 100)
counter.views += 1
counter.save()

# Watęk B (+2 po Wątku B)
counter = Counter.objects.
select_for_update().get(pk= 1)
counter.views += 1
counter.save()
SELECT … FOR UPDATE
● select_for_update tylko gdy będzie update
● w django od wersji 1.4
● lub na podstawie snippeta https:
//djangosnippets.org/snippets/2766/ w
django < 1.4
Co jest nie tak z .save()
W pewnym frameworku podczas logowania…
# django/contrib/auth/models.py
def update_last_login(sender, user,
**kwargs):
user.last_login = timezone.now()
user.save()

UPDATE `auth_user` SET
`username` = %s, `first_name` =
%s, `last_name` = %s, `email` =
%s, `password` = %s, `is_staff`
= %s, `is_active` = %s,
`is_superuser` = %s,
`last_login` = %s, `date_joined`
= %s WHERE `auth_user`.`id` = %s
Dlaczego taki save jest zły ?
● brak kontroli nad tym co jest zapisywane do
bazy
● wydajność bazy danych
● nadpisywanie zmian (cudzych)
● utrudnia debugowanie - serio!
● django.admin :(
Model.save (the right way)
● Użycie save(update_fields=[..]) - trudne w
utrzymaniu!
● Użycie django-dirtyfields + własny save
● Własny update(field=val,..)
TransactionMiddleware (depercated)
It works like this: When a request starts, Django
starts a transaction. If the response is produced
without problems, Django commits any pending
transactions
docs.djangoproject.com
TransactionMiddleware
def home(request):
Counter.objects.update(views= 1)
foo()
bar()
@transaction.commit_on_success
def foo():
Counter.objects.update(views= 2)
@transaction.commit_on_success
def bar():
Counter.objects.update(views= 3)
raise ValueError

BEGIN
UPDATE "bar_counter" SET "views" = 1
UPDATE "bar_counter" SET "views" = 2
COMMIT
BEGIN
UPDATE "bar_counter" SET "views" = 3
ROLLBACK
Testy w Django
● domyślnie TestCase nie działa
transakcyjnie!
● TransactionTestCase gdy testujemy kod
transakcyjny
● Jak testować transakcyjność?
Pytania ?
kontakt@marcinbaran.be
Dziękuje za uwagę!

Weitere ähnliche Inhalte

Was ist angesagt?

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
Soós Gábor
 

Was ist angesagt? (20)

Up and Running with ReactJS
Up and Running with ReactJSUp and Running with ReactJS
Up and Running with ReactJS
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
Angularjs Anti-patterns
Angularjs Anti-patternsAngularjs Anti-patterns
Angularjs Anti-patterns
 
Introducing AngularJS
Introducing AngularJSIntroducing AngularJS
Introducing AngularJS
 
AngularJS best-practices
AngularJS best-practicesAngularJS best-practices
AngularJS best-practices
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angularjs Performance
Angularjs PerformanceAngularjs Performance
Angularjs Performance
 
Dart and AngularDart
Dart and AngularDartDart and AngularDart
Dart and AngularDart
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routing
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Dive into AngularJS and directives
Dive into AngularJS and directivesDive into AngularJS and directives
Dive into AngularJS and directives
 
Aspdevice - Asp Fast Crud introdution
Aspdevice - Asp Fast Crud introdutionAspdevice - Asp Fast Crud introdution
Aspdevice - Asp Fast Crud introdution
 
The Future of CSS with Web Components
The Future of CSS with Web ComponentsThe Future of CSS with Web Components
The Future of CSS with Web Components
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 

Andere mochten auch

AngularJS szkolenie wewnętrzne (into)
AngularJS szkolenie wewnętrzne (into)AngularJS szkolenie wewnętrzne (into)
AngularJS szkolenie wewnętrzne (into)
Marcin Baran
 
Apache http server - proste i zaawansowane przypadki użycia
Apache http server - proste i zaawansowane przypadki użyciaApache http server - proste i zaawansowane przypadki użycia
Apache http server - proste i zaawansowane przypadki użycia
Wojciech Lichota
 
Pyra stxnext
Pyra stxnextPyra stxnext
Pyra stxnext
radekj200
 
Raspberry pi - tiny hardware, huge idea
Raspberry pi - tiny hardware, huge ideaRaspberry pi - tiny hardware, huge idea
Raspberry pi - tiny hardware, huge idea
Wojciech Lichota
 

Andere mochten auch (13)

Jak przygotować się do rozmowy rekrutacyjnej na Python Developera
Jak przygotować się do rozmowy rekrutacyjnej na Python DeveloperaJak przygotować się do rozmowy rekrutacyjnej na Python Developera
Jak przygotować się do rozmowy rekrutacyjnej na Python Developera
 
Jak działa CPython
Jak działa CPythonJak działa CPython
Jak działa CPython
 
AngularJS szkolenie wewnętrzne (into)
AngularJS szkolenie wewnętrzne (into)AngularJS szkolenie wewnętrzne (into)
AngularJS szkolenie wewnętrzne (into)
 
Grok Artykul
Grok ArtykulGrok Artykul
Grok Artykul
 
Sandman - makes things REST
Sandman - makes things RESTSandman - makes things REST
Sandman - makes things REST
 
Compiled Websites with Plone, Django, Xapian and SSI
Compiled Websites with Plone, Django, Xapian and SSICompiled Websites with Plone, Django, Xapian and SSI
Compiled Websites with Plone, Django, Xapian and SSI
 
Grok Prezentacja
Grok PrezentacjaGrok Prezentacja
Grok Prezentacja
 
Apache http server - proste i zaawansowane przypadki użycia
Apache http server - proste i zaawansowane przypadki użyciaApache http server - proste i zaawansowane przypadki użycia
Apache http server - proste i zaawansowane przypadki użycia
 
Zwinność procesu rekrutacyjnego w branży IT
Zwinność procesu rekrutacyjnego w branży ITZwinność procesu rekrutacyjnego w branży IT
Zwinność procesu rekrutacyjnego w branży IT
 
Pyra stxnext
Pyra stxnextPyra stxnext
Pyra stxnext
 
Raspberry pi - tiny hardware, huge idea
Raspberry pi - tiny hardware, huge ideaRaspberry pi - tiny hardware, huge idea
Raspberry pi - tiny hardware, huge idea
 
Anty-wzorce w różnorodności w branży it
Anty-wzorce w różnorodności w branży itAnty-wzorce w różnorodności w branży it
Anty-wzorce w różnorodności w branży it
 
Continuous Deployment aplikacji w Django
Continuous Deployment aplikacji w DjangoContinuous Deployment aplikacji w Django
Continuous Deployment aplikacji w Django
 

Ähnlich wie Transakcyjność w django

Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
Leonardo Soto
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
diego_k
 
Curscatalyst
CurscatalystCurscatalyst
Curscatalyst
Kar Juan
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
Yehuda Katz
 

Ähnlich wie Transakcyjność w django (20)

Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Optimization in django orm
Optimization in django ormOptimization in django orm
Optimization in django orm
 
What's new in Django 1.2?
What's new in Django 1.2?What's new in Django 1.2?
What's new in Django 1.2?
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
 
Curscatalyst
CurscatalystCurscatalyst
Curscatalyst
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Hacking Movable Type
Hacking Movable TypeHacking Movable Type
Hacking Movable Type
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFaces
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
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
 
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
 

Kürzlich hochgeladen (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
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
 
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
 
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
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Transakcyjność w django

  • 1. Transakcyjność w Django Marcin Baran @Sharpekk internetowykantor.pl
  • 3. W pewnej aplikacji w Django.. @transaction.commit_on_success def run(): Counter.objects.update(views= 1) foo() bar() @transaction.commit_on_success def foo(): Counter.objects.update(views= 2) @transaction.commit_on_success def bar(): Counter.objects.update(views= 3) BEGIN UPDATE "bar_counter" SET "views" = 1 UPDATE "bar_counter" SET "views" = 2 COMMIT BEGIN UPDATE "bar_counter" SET "views" = 3 COMMIT
  • 4. #HEHESZKA ;-) BEGIN UPDATE "bar_counter" SET "views" = 1 UPDATE "bar_counter" SET "views" = 2 COMMIT BEGIN UPDATE "bar_counter" SET "views" = 3 COMMIT
  • 5. @commit_on_success_unless_managed @commit_on_success_unless_managed def run(): Counter.objects.update(views= 1) foo() bar() @commit_on_success_unless_managed def foo(): Counter.objects.update(views= 2) @commit_on_success_unless_managed def bar(): Counter.objects.update(views= 3) BEGIN UPDATE "bar_counter" SET "views" = 1 UPDATE "bar_counter" SET "views" = 2 UPDATE "bar_counter" SET "views" = 3 COMMIT
  • 6. Race Condition Counter.objects.update(views= 1) # Watęk A (w tym samym czasie) # Watęk B (w tym samym czasie) counter = Counter.objects.get(pk= 1) counter = Counter.objects.get(pk= 1) counter.views += 1 counter.save() print Couter.objects.get(pk= 1).counter >>> 2 counter.views += 1 counter.save()
  • 7. SELECT … FOR UPDATE print Counter.objects.update(views= 1) # Watęk A counter = Counter.objects. select_for_update().get(pk= 1) time.sleep( 100) counter.views += 1 counter.save() # Watęk B (+2 po Wątku B) counter = Counter.objects. select_for_update().get(pk= 1) counter.views += 1 counter.save()
  • 8. SELECT … FOR UPDATE ● select_for_update tylko gdy będzie update ● w django od wersji 1.4 ● lub na podstawie snippeta https: //djangosnippets.org/snippets/2766/ w django < 1.4
  • 9. Co jest nie tak z .save() W pewnym frameworku podczas logowania… # django/contrib/auth/models.py def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save() UPDATE `auth_user` SET `username` = %s, `first_name` = %s, `last_name` = %s, `email` = %s, `password` = %s, `is_staff` = %s, `is_active` = %s, `is_superuser` = %s, `last_login` = %s, `date_joined` = %s WHERE `auth_user`.`id` = %s
  • 10. Dlaczego taki save jest zły ? ● brak kontroli nad tym co jest zapisywane do bazy ● wydajność bazy danych ● nadpisywanie zmian (cudzych) ● utrudnia debugowanie - serio! ● django.admin :(
  • 11. Model.save (the right way) ● Użycie save(update_fields=[..]) - trudne w utrzymaniu! ● Użycie django-dirtyfields + własny save ● Własny update(field=val,..)
  • 12. TransactionMiddleware (depercated) It works like this: When a request starts, Django starts a transaction. If the response is produced without problems, Django commits any pending transactions docs.djangoproject.com
  • 13. TransactionMiddleware def home(request): Counter.objects.update(views= 1) foo() bar() @transaction.commit_on_success def foo(): Counter.objects.update(views= 2) @transaction.commit_on_success def bar(): Counter.objects.update(views= 3) raise ValueError BEGIN UPDATE "bar_counter" SET "views" = 1 UPDATE "bar_counter" SET "views" = 2 COMMIT BEGIN UPDATE "bar_counter" SET "views" = 3 ROLLBACK
  • 14. Testy w Django ● domyślnie TestCase nie działa transakcyjnie! ● TransactionTestCase gdy testujemy kod transakcyjny ● Jak testować transakcyjność?