SlideShare a Scribd company logo
1 of 22
Hexagonal Design in Django
Maarten van Schaik
Django
• Rapid application development
• ./manage.py startapp polls
• Define some models, forms, views and we’re
in business!
Applications live and grow
• More features are added:
– API access
– Reporting
– Command Line Interface
– Integration with other applications
– Who knows what else…
Connected Design
• Components can access all other components
• When you need to access a piece of data or a
piece of logic, just import and use it
• Development is fast
Modular design
• Access to other components goes through
well-defined interfaces (API’s) using well-
defined protocols
• Components have high cohesion
• Components are loosely
coupled
Connected vs Modular
Ports and Adapters
Ports and Adapters
• Specific adapter for each use of the
application, e.g. web view, command line,
message queue, etc.
• Each adapter connects to a port of the
application
• Mock adapters and test harnesses facilitate
testing
• Testing becomes easier and faster
Typical Django app
• __init__.py
• admin.py
• forms.py
• models.py
• tests.py
• urls.py
• views.py
App
Uh oh…
• Where is my application?
??
Models
Views
Forms
Refactoring Django apps
• Rules
– Core domain model cannot depend on Django
– Tell objects, ask values
Implications
• Core model cannot depend on framework
– Core model cannot derive from models.Model
– Communication with Django goes through
adapters
• Tell, don’t ask
– Views should render from immutable values
– So no vote.save() in views.py!
Example – Poll
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(
pk=request.POST*‘choice’+)
except (KeyError, Choice.DoesNotExist):
return render(request, …, ,error: …-)
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(…)
Example – Poll
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(
pk=request.POST*‘choice’+)
except (KeyError, Choice.DoesNotExist):
return render(request, …, ,error: …-)
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(…)
Mutating data!
Example – Poll (2)
def vote(request, poll_id):
try:
poll_engine.register_vote(poll_id, request.POST*‘choice’+)
except Exception as e:
return render(request, …, ,error: …-)
else:
return HttpResponseRedirect(…)
Example – Poll (2)
## Poll engine
def register_vote(poll_id, choice_id):
p = Poll.objects.get(pk=poll_id)
selected_choice = p.choice_set.get(pk=choice_id)
selected_choice.votes += 1
selected_choice.save()
Example – Poll (2)
## Poll engine
def register_vote(poll_id, choice_id):
p = Poll.objects.get(pk=poll_id)
selected_choice = p.choice_set.get(pk=choice_id)
selected_choice.votes += 1
selected_choice.save()
Dependency on Django models
Example – Poll (3)
## Poll engine
def register_vote(poll_id, choice_id):
if not poll_repository.choice_exists(poll_id, choice_id):
raise PollException(…)
poll_repository.increment_vote_count(choice_id)
Example – Poll (3)
## Django model adapter
def choice_exists(poll_id, choice_id):
return Choice.objects.filter(
poll_id=poll_id, pk=choice_id).exists()
def increment_vote_count(choice_id)
Choice.objects.filter(pk=choice_id).update(
votes=F(‘votes’)+1)
Conclusions
• Hexagonal design will help keep speed of
adding new features constant
• Encourages modularity and encapsulation
• Encourages clean and well-organized
applications
• Tests become faster when using plain objects
and data
• Django models are not that useful without
coupling with them
That’s it
Thanks and references
• Matt Wynne: Hexagonal Rails
• Kent Beck: To Design or Not To Design?
• Alistair Cockburn: Hexagonal Architecture
• Django tutorial

More Related Content

What's hot

The Integration of Laravel with Swoole
The Integration of Laravel with SwooleThe Integration of Laravel with Swoole
The Integration of Laravel with SwooleAlbert Chen
 
Pragmatic RESTful API Design: Apigee Webinar
Pragmatic RESTful API Design: Apigee WebinarPragmatic RESTful API Design: Apigee Webinar
Pragmatic RESTful API Design: Apigee WebinarApigee | Google Cloud
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
API Test Automation
API Test Automation API Test Automation
API Test Automation SQALab
 
Microservice architecture : Part 1
Microservice architecture : Part 1Microservice architecture : Part 1
Microservice architecture : Part 1NodeXperts
 
The state of passwordless auth on the web
The state of passwordless auth on the web The state of passwordless auth on the web
The state of passwordless auth on the web Phil Nash
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
Self healing test automation with Healenium and Minimization of regression su...
Self healing test automation with Healenium and Minimization of regression su...Self healing test automation with Healenium and Minimization of regression su...
Self healing test automation with Healenium and Minimization of regression su...Dmitriy Gumeniuk
 
Postman: An Introduction for Testers
Postman: An Introduction for TestersPostman: An Introduction for Testers
Postman: An Introduction for TestersPostman
 
Odoo's Test Framework - Learn Best Practices
Odoo's Test Framework - Learn Best PracticesOdoo's Test Framework - Learn Best Practices
Odoo's Test Framework - Learn Best PracticesOdoo
 
Micro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - PlansoftMicro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - PlansoftMiki Lombardi
 
A python web service
A python web serviceA python web service
A python web serviceTemian Vlad
 
Microservices
MicroservicesMicroservices
MicroservicesSmartBear
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak Abhishek Koserwal
 

What's hot (20)

Rest API
Rest APIRest API
Rest API
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
The Integration of Laravel with Swoole
The Integration of Laravel with SwooleThe Integration of Laravel with Swoole
The Integration of Laravel with Swoole
 
Pragmatic RESTful API Design: Apigee Webinar
Pragmatic RESTful API Design: Apigee WebinarPragmatic RESTful API Design: Apigee Webinar
Pragmatic RESTful API Design: Apigee Webinar
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
API Test Automation
API Test Automation API Test Automation
API Test Automation
 
Api Gateway
Api GatewayApi Gateway
Api Gateway
 
Microservice architecture : Part 1
Microservice architecture : Part 1Microservice architecture : Part 1
Microservice architecture : Part 1
 
The state of passwordless auth on the web
The state of passwordless auth on the web The state of passwordless auth on the web
The state of passwordless auth on the web
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Self healing test automation with Healenium and Minimization of regression su...
Self healing test automation with Healenium and Minimization of regression su...Self healing test automation with Healenium and Minimization of regression su...
Self healing test automation with Healenium and Minimization of regression su...
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
Postman: An Introduction for Testers
Postman: An Introduction for TestersPostman: An Introduction for Testers
Postman: An Introduction for Testers
 
API TESTING
API TESTINGAPI TESTING
API TESTING
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Odoo's Test Framework - Learn Best Practices
Odoo's Test Framework - Learn Best PracticesOdoo's Test Framework - Learn Best Practices
Odoo's Test Framework - Learn Best Practices
 
Micro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - PlansoftMicro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - Plansoft
 
A python web service
A python web serviceA python web service
A python web service
 
Microservices
MicroservicesMicroservices
Microservices
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak
 

Viewers also liked

Domain Driven Design com Python
Domain Driven Design com PythonDomain Driven Design com Python
Domain Driven Design com PythonFrederico Cabral
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDDennis Doomen
 
Архитектура RESTful API на Pyramid — приемы проектирования Дмитрий Вахрушев
Архитектура RESTful API на Pyramid — приемы проектирования Дмитрий ВахрушевАрхитектура RESTful API на Pyramid — приемы проектирования Дмитрий Вахрушев
Архитектура RESTful API на Pyramid — приемы проектирования Дмитрий Вахрушевit-people
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
 
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST""Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"PyNSK
 
Sofware Fora de Séria 2016 - Implementando realtime no frontend
Sofware Fora de Séria 2016 - Implementando realtime no frontendSofware Fora de Séria 2016 - Implementando realtime no frontend
Sofware Fora de Séria 2016 - Implementando realtime no frontendWilliam Seiti Mizuta
 
Package and distribute your Python code
Package and distribute your Python codePackage and distribute your Python code
Package and distribute your Python codeSanket Saurav
 
Driven Development - Closing the Loop on Scrum
Driven Development - Closing the Loop on ScrumDriven Development - Closing the Loop on Scrum
Driven Development - Closing the Loop on ScrumAdam Englander
 
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014Python Meetup
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?Inada Naoki
 
Como DDD e Strategic Design estão nos ajudando a modernizar um Legado
Como DDD e Strategic Design estão nos ajudando a modernizar um LegadoComo DDD e Strategic Design estão nos ajudando a modernizar um Legado
Como DDD e Strategic Design estão nos ajudando a modernizar um LegadoLuiz Costa
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for PythonTimo Stollenwerk
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humansCraig Kerstiens
 
Moving from Django Apps to Services
Moving from Django Apps to ServicesMoving from Django Apps to Services
Moving from Django Apps to ServicesCraig Kerstiens
 
Introduction to hexagonal architecture
Introduction to hexagonal architectureIntroduction to hexagonal architecture
Introduction to hexagonal architectureManel Sellés
 
DDD session BrownBagLunch (FR)
DDD session BrownBagLunch (FR)DDD session BrownBagLunch (FR)
DDD session BrownBagLunch (FR)Cyrille Martraire
 
Developing Software As A Service App with Python & Django
Developing Software As A Service App with Python & DjangoDeveloping Software As A Service App with Python & Django
Developing Software As A Service App with Python & DjangoAllan Mangune
 

Viewers also liked (20)

Domain Driven Design com Python
Domain Driven Design com PythonDomain Driven Design com Python
Domain Driven Design com Python
 
Python SOLID
Python SOLIDPython SOLID
Python SOLID
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDD
 
Архитектура RESTful API на Pyramid — приемы проектирования Дмитрий Вахрушев
Архитектура RESTful API на Pyramid — приемы проектирования Дмитрий ВахрушевАрхитектура RESTful API на Pyramid — приемы проектирования Дмитрий Вахрушев
Архитектура RESTful API на Pyramid — приемы проектирования Дмитрий Вахрушев
 
Pyramid tutorial
Pyramid tutorialPyramid tutorial
Pyramid tutorial
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST""Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
 
Sofware Fora de Séria 2016 - Implementando realtime no frontend
Sofware Fora de Séria 2016 - Implementando realtime no frontendSofware Fora de Séria 2016 - Implementando realtime no frontend
Sofware Fora de Séria 2016 - Implementando realtime no frontend
 
Package and distribute your Python code
Package and distribute your Python codePackage and distribute your Python code
Package and distribute your Python code
 
Driven Development - Closing the Loop on Scrum
Driven Development - Closing the Loop on ScrumDriven Development - Closing the Loop on Scrum
Driven Development - Closing the Loop on Scrum
 
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?
 
Como DDD e Strategic Design estão nos ajudando a modernizar um Legado
Como DDD e Strategic Design estão nos ajudando a modernizar um LegadoComo DDD e Strategic Design estão nos ajudando a modernizar um Legado
Como DDD e Strategic Design estão nos ajudando a modernizar um Legado
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for Python
 
Organise a Code Dojo!
Organise a Code Dojo!Organise a Code Dojo!
Organise a Code Dojo!
 
Postgres performance for humans
Postgres performance for humansPostgres performance for humans
Postgres performance for humans
 
Moving from Django Apps to Services
Moving from Django Apps to ServicesMoving from Django Apps to Services
Moving from Django Apps to Services
 
Introduction to hexagonal architecture
Introduction to hexagonal architectureIntroduction to hexagonal architecture
Introduction to hexagonal architecture
 
DDD session BrownBagLunch (FR)
DDD session BrownBagLunch (FR)DDD session BrownBagLunch (FR)
DDD session BrownBagLunch (FR)
 
Developing Software As A Service App with Python & Django
Developing Software As A Service App with Python & DjangoDeveloping Software As A Service App with Python & Django
Developing Software As A Service App with Python & Django
 

Similar to Hexagonal Design in Django

External Data in Puppet 4
External Data in Puppet 4External Data in Puppet 4
External Data in Puppet 4ripienaar
 
PuppetConf. 2016: External Data in Puppet 4 – R.I. Pienaar
PuppetConf. 2016: External Data in Puppet 4 – R.I. PienaarPuppetConf. 2016: External Data in Puppet 4 – R.I. Pienaar
PuppetConf. 2016: External Data in Puppet 4 – R.I. PienaarPuppet
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API designmeij200
 
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimMir Nazim
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTTkevinvw
 
PyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdf
PyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdfPyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdf
PyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdfJim Dowling
 
Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...
Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...
Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...Precisely
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030Kevin Wu
 
Utilisation de MLflow pour le cycle de vie des projet Machine learning
Utilisation de MLflow pour le cycle de vie des projet Machine learningUtilisation de MLflow pour le cycle de vie des projet Machine learning
Utilisation de MLflow pour le cycle de vie des projet Machine learningParis Data Engineers !
 
Machine learning in action at Pipedrive
Machine learning in action at PipedriveMachine learning in action at Pipedrive
Machine learning in action at PipedriveAndré Karpištšenko
 
Play framework: lessons learned
Play framework: lessons learnedPlay framework: lessons learned
Play framework: lessons learnedPeter Hilton
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesTao Xie
 
Maximizer 2018 API training
Maximizer 2018 API trainingMaximizer 2018 API training
Maximizer 2018 API trainingMurylo Batista
 
Practices and tools for building better APIs
Practices and tools for building better APIsPractices and tools for building better APIs
Practices and tools for building better APIsNLJUG
 

Similar to Hexagonal Design in Django (20)

Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Autoforms
AutoformsAutoforms
Autoforms
 
External Data in Puppet 4
External Data in Puppet 4External Data in Puppet 4
External Data in Puppet 4
 
PuppetConf. 2016: External Data in Puppet 4 – R.I. Pienaar
PuppetConf. 2016: External Data in Puppet 4 – R.I. PienaarPuppetConf. 2016: External Data in Puppet 4 – R.I. Pienaar
PuppetConf. 2016: External Data in Puppet 4 – R.I. Pienaar
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API design
 
IGears: Template Architecture and Principles
IGears: Template Architecture and PrinciplesIGears: Template Architecture and Principles
IGears: Template Architecture and Principles
 
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
 
PyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdf
PyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdfPyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdf
PyCon Sweden 2022 - Dowling - Serverless ML with Hopsworks.pdf
 
Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...
Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...
Automate Studio Training: Materials Maintenance Tips for Efficiency and Ease ...
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Utilisation de MLflow pour le cycle de vie des projet Machine learning
Utilisation de MLflow pour le cycle de vie des projet Machine learningUtilisation de MLflow pour le cycle de vie des projet Machine learning
Utilisation de MLflow pour le cycle de vie des projet Machine learning
 
Python Open Session.pptx
Python Open Session.pptxPython Open Session.pptx
Python Open Session.pptx
 
Machine learning in action at Pipedrive
Machine learning in action at PipedriveMachine learning in action at Pipedrive
Machine learning in action at Pipedrive
 
Play framework: lessons learned
Play framework: lessons learnedPlay framework: lessons learned
Play framework: lessons learned
 
Tango with django
Tango with djangoTango with django
Tango with django
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
 
Maximizer 2018 API training
Maximizer 2018 API trainingMaximizer 2018 API training
Maximizer 2018 API training
 
Practices and tools for building better APIs
Practices and tools for building better APIsPractices and tools for building better APIs
Practices and tools for building better APIs
 

Recently uploaded

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
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 WorkerThousandEyes
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
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 textsMaria Levchenko
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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 Servicegiselly40
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Recently uploaded (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 

Hexagonal Design in Django

  • 1. Hexagonal Design in Django Maarten van Schaik
  • 2. Django • Rapid application development • ./manage.py startapp polls • Define some models, forms, views and we’re in business!
  • 3. Applications live and grow • More features are added: – API access – Reporting – Command Line Interface – Integration with other applications – Who knows what else…
  • 4. Connected Design • Components can access all other components • When you need to access a piece of data or a piece of logic, just import and use it • Development is fast
  • 5. Modular design • Access to other components goes through well-defined interfaces (API’s) using well- defined protocols • Components have high cohesion • Components are loosely coupled
  • 8. Ports and Adapters • Specific adapter for each use of the application, e.g. web view, command line, message queue, etc. • Each adapter connects to a port of the application • Mock adapters and test harnesses facilitate testing • Testing becomes easier and faster
  • 9. Typical Django app • __init__.py • admin.py • forms.py • models.py • tests.py • urls.py • views.py
  • 10. App Uh oh… • Where is my application? ?? Models Views Forms
  • 11. Refactoring Django apps • Rules – Core domain model cannot depend on Django – Tell objects, ask values
  • 12. Implications • Core model cannot depend on framework – Core model cannot derive from models.Model – Communication with Django goes through adapters • Tell, don’t ask – Views should render from immutable values – So no vote.save() in views.py!
  • 13. Example – Poll def vote(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) try: selected_choice = p.choice_set.get( pk=request.POST*‘choice’+) except (KeyError, Choice.DoesNotExist): return render(request, …, ,error: …-) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(…)
  • 14. Example – Poll def vote(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) try: selected_choice = p.choice_set.get( pk=request.POST*‘choice’+) except (KeyError, Choice.DoesNotExist): return render(request, …, ,error: …-) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(…) Mutating data!
  • 15. Example – Poll (2) def vote(request, poll_id): try: poll_engine.register_vote(poll_id, request.POST*‘choice’+) except Exception as e: return render(request, …, ,error: …-) else: return HttpResponseRedirect(…)
  • 16. Example – Poll (2) ## Poll engine def register_vote(poll_id, choice_id): p = Poll.objects.get(pk=poll_id) selected_choice = p.choice_set.get(pk=choice_id) selected_choice.votes += 1 selected_choice.save()
  • 17. Example – Poll (2) ## Poll engine def register_vote(poll_id, choice_id): p = Poll.objects.get(pk=poll_id) selected_choice = p.choice_set.get(pk=choice_id) selected_choice.votes += 1 selected_choice.save() Dependency on Django models
  • 18. Example – Poll (3) ## Poll engine def register_vote(poll_id, choice_id): if not poll_repository.choice_exists(poll_id, choice_id): raise PollException(…) poll_repository.increment_vote_count(choice_id)
  • 19. Example – Poll (3) ## Django model adapter def choice_exists(poll_id, choice_id): return Choice.objects.filter( poll_id=poll_id, pk=choice_id).exists() def increment_vote_count(choice_id) Choice.objects.filter(pk=choice_id).update( votes=F(‘votes’)+1)
  • 20. Conclusions • Hexagonal design will help keep speed of adding new features constant • Encourages modularity and encapsulation • Encourages clean and well-organized applications • Tests become faster when using plain objects and data • Django models are not that useful without coupling with them
  • 22. Thanks and references • Matt Wynne: Hexagonal Rails • Kent Beck: To Design or Not To Design? • Alistair Cockburn: Hexagonal Architecture • Django tutorial