SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopSudhir Tonse
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean ArchitectureBadoo
 
Kata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and AdaptersKata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and Adaptersholsky
 
RESTful services
RESTful servicesRESTful services
RESTful servicesgouthamrv
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Understanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsTessa Mero
 
Introducing Clean Architecture
Introducing Clean ArchitectureIntroducing Clean Architecture
Introducing Clean ArchitectureRoc Boronat
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript FundamentalsSunny Sharma
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to SwaggerKnoldus Inc.
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
 

Mais procurados (20)

Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Kata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and AdaptersKata: Hexagonal Architecture / Ports and Adapters
Kata: Hexagonal Architecture / Ports and Adapters
 
RESTful services
RESTful servicesRESTful services
RESTful services
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Adr intro
Adr introAdr intro
Adr intro
 
Clean code
Clean codeClean code
Clean code
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Understanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple Steps
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Introducing Clean Architecture
Introducing Clean ArchitectureIntroducing Clean Architecture
Introducing Clean Architecture
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
React JS
React JSReact JS
React JS
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
Api presentation
Api presentationApi presentation
Api presentation
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 

Destaque

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
 
Code & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignCode & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignFrank Levering
 

Destaque (20)

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
 
Code & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignCode & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven Design
 

Semelhante a 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
 

Semelhante a 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
 

Último

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
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
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Último (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

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