SlideShare a Scribd company logo
1 of 16
Download to read offline
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ę!

More Related Content

What's hot

Up and Running with ReactJS
Up and Running with ReactJSUp and Running with ReactJS
Up and Running with ReactJSLoc Nguyen
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPressCaldera Labs
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widgetTudor Barbu
 
Angularjs Anti-patterns
Angularjs Anti-patternsAngularjs Anti-patterns
Angularjs Anti-patternsSteven Lambert
 
Introducing AngularJS
Introducing AngularJSIntroducing AngularJS
Introducing AngularJSLoc Nguyen
 
AngularJS best-practices
AngularJS best-practicesAngularJS best-practices
AngularJS best-practicesHenry Tao
 
Dart and AngularDart
Dart and AngularDartDart and AngularDart
Dart and AngularDartLoc Nguyen
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJsTudor Barbu
 
Angular directive filter and routing
Angular directive filter and routingAngular directive filter and routing
Angular directive filter and routingjagriti srivastava
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Aspdevice - Asp Fast Crud introdution
Aspdevice - Asp Fast Crud introdutionAspdevice - Asp Fast Crud introdution
Aspdevice - Asp Fast Crud introdutionAdriano Mendes
 
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 ComponentsColdFusionConference
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish MinutesDan Wahlin
 

What's hot (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
 

Viewers also liked

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 DeveloperaWojciech Lichota
 
AngularJS szkolenie wewnętrzne (into)
AngularJS szkolenie wewnętrzne (into)AngularJS szkolenie wewnętrzne (into)
AngularJS szkolenie wewnętrzne (into)Marcin Baran
 
Sandman - makes things REST
Sandman - makes things RESTSandman - makes things REST
Sandman - makes things RESTWojciech Lichota
 
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 SSIWojciech Lichota
 
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życiaWojciech Lichota
 
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 ITSTX Next
 
Pyra stxnext
Pyra stxnextPyra stxnext
Pyra stxnextradekj200
 
Raspberry pi - tiny hardware, huge idea
Raspberry pi - tiny hardware, huge ideaRaspberry pi - tiny hardware, huge idea
Raspberry pi - tiny hardware, huge ideaWojciech Lichota
 
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 itAgata Landzwójczak
 
Continuous Deployment aplikacji w Django
Continuous Deployment aplikacji w DjangoContinuous Deployment aplikacji w Django
Continuous Deployment aplikacji w DjangoWojciech Lichota
 

Viewers also liked (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
 

Similar to Transakcyjność w django

Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsLeonardo Soto
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
Optimization in django orm
Optimization in django ormOptimization in django orm
Optimization in django ormDenys Levchenko
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworksdiego_k
 
Curscatalyst
CurscatalystCurscatalyst
CurscatalystKar Juan
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
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 websitesLindsay Holmwood
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkara JUG
 

Similar to 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
 

Recently uploaded

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 

Recently uploaded (20)

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 

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ść?