SlideShare une entreprise Scribd logo
1  sur  99
Télécharger pour lire hors ligne
Writing reusable applications

James Bennett


DjangoCon, Mountain View, CA,
September 6, 2008
The extended remix!
The fourfold path

 Do one thing, and do it well.
 Don’t be afraid of multiple apps.
 Write for flexibility.
 Build to distribute.
1
“   Do one thing, and do it well.




                                         ”
                             -- The UNIX philosophy
Application ==
encapsulation
Keep a tight focus

 Ask yourself: “What does this application
 do?”
 Answer should be one or two short
 sentences
Good focus

 “Handle storage of users and authentication
 of their identities.”
 “Allow content to be tagged, del.icio.us
 style, with querying by tags.”
 “Handle entries in a weblog.”
Bad focus

 “Handle entries in a weblog, and users who
 post them, and their authentication, and
 tagging and categorization, and some flat
 pages for static content, and...”
 The coding equivalent of a run-on sentence
Warning signs

 A lot of very good Django applications are
 very small: just a few files
 If your app is getting big enough to need
 lots of things split up into lots of modules, it
 may be time to step back and re-evaluate
Warning signs
 Even a lot of “simple” Django sites
 commonly have a dozen or more
 applications in INSTALLED_APPS
 If you’ve got a complex/feature-packed
 site and a short application list, it may be
 time to think hard about how tightly-
 focused those apps are
Case study: user
  registration
Features


 User fills out form, inactive account created
 User gets email with link, clicks to activate
 And that’s it
User registration

 Different sites want different information
 Different types of users
 Different signup workflow
 Etc., etc.
Some “simple” things
  aren’t so simple.
Approach features
   skeptically
Should I add this
feature?

 What does the application do?
 Does this feature have anything to do with
 that?
 No? Guess I shouldn’t add it, then.
Top feature request in
 django-registration:
     User profiles
“
What does that have to do with user
          registration?




                                 ”-- Me
The solution?
django-profiles

 Add profile
 Edit profile
 View profile
 And that’s it.
2
Don’t be afraid of
 multiple apps
The monolith mindset
 The “application” is the whole site
 Re-use is often an afterthought
 Tend to develop plugins that hook into the
 “main” application
 Or make heavy use of middleware-like
 concepts
The Django mindset


 Application == some bit of functionality
 Site == several applications
 Tend to spin off new applications liberally
Django encourages this
 Instead of one “application”, a list:
 INSTALLED_APPS
 Applications live on the Python path, not
 inside any specific “apps” or “plugins”
 directory
 Abstractions like the Site model make you
 think about this as you develop
Should this be its own
application?
 Is it completely unrelated to the app’s
 focus?
 Is it orthogonal to whatever else I’m doing?
 Will I need similar functionality on other
 sites?
 Yes? Then I should break it out into a
 separate application.
Unrelated features

 Feature creep is tempting: “but wouldn’t it
 be cool if...”
 But it’s the road to Hell
 See also: Part 1 of this talk
I’ve learned this the
      hard way
djangosnippets.org

 One application
 Includes bookmarking features
 Includes tagging features
 Includes rating features
Should be about four
   applications
So I wrote a book
telling people not to do
        what I did
Page 210, in case you
  were wondering.
Orthogonality
 Means you can change one thing without
 affecting others
 Almost always indicates the need for a
 separate application
 Example: changing user profile workflow
 doesn’t affect user signup workflow. Make
 them two different applications.
Reuse

 Lots of cool features actually aren’t specific
 to one site
 See: bookmarking, tagging, rating...
 Why bring all this crap about code snippets
 along just to get the extra stuff?
Case study: blogging
I wanted a blog
 Entries and links
 Tagging
 Comments with moderation
 Contact form
 “About” page
 Etc., etc.
I ended up with
 A blog app (entries and links)
 A third-party tagging app
 contrib.comments + moderation app
 A contact-form app
 contrib.flatpages
 Etc., etc.
Advantages


 Don’t keep rewriting features
 Drop things into other sites easily
Need a contact form?
urlpatterns += (‘’,
    (r’^contact/’, include(‘contact_form.urls’)),
)
And you’re done
But what about...
Site-specific needs

 Site A wants a contact form that just
 collects a message.
 Site B’s marketing department wants a
 bunch of info.
 Site C wants to use Akismet to filter
 automated spam.
3
Write for flexibility
Common sense


 Sane defaults
 Easy overrides
 Don’t set anything in stone
Form processing


 Supply a form class
 But let people specify their own if they
 want
class SomeForm(forms.Form):
    ...

def process_form(request, form_class=SomeForm):
    if request.method == ‘POST’:
        form = form_class(request.POST)
        ...
    else:
        form = form_class()
    ...
Templates


 Specify a default template
 But let people specify their own if they
 want
def process_form(request, form_class=SomeForm,
                 template_name=’do_form.html’):
    ...
    return render_to_response(template_name,
                              ...
Form processing

 You want to redirect after successful
 submission
 Supply a default URL
 But let people specify their own if they
 want
def process_form(request, form_class=SomeForm,
                 template_name=’do_form.html’,
                 success_url=’/foo/’):
    ...
    return HttpResponseRedirect(success_url)
URL best practices

 Provide a URLConf in the application
 Use named URL patterns
 Use reverse lookups: reverse(),
 permalink, {% url %}
Working with models

 Whenever possible, avoid hard-coding a
 model class
 Use get_model() and take an app label/
 model name string instead
 Don’t rely on objects; use the default
 manager
from django.db.models import get_model

def get_object(model_str, pk):
    model = get_model(*model_str.split(‘.’))
    return model._default_manager.get(pk=pk)

user_12 = get_object(‘auth.user’, 12)
Working with models

 Don’t hard-code fields or table names;
 introspect the model to get those
 Accept lookup arguments you can pass
 straight through to the database API
Learn to love managers

 Managers are easy to reuse.
 Managers are easy to subclass and
 customize.
 Managers let you encapsulate patterns of
 behavior behind a nice API.
Advanced techniques

 Encourage subclassing and use of
 subclasses
 Provide a standard interface people can
 implement in place of your default
 implementation
 Use a registry (like the admin)
The API your
 application exposes is
just as important as the
   design of the sites
     you’ll use it in.
In fact, it’s more
    important.
Good API design
 “Pass in a value for this argument to change
 the behavior”
 “Change the value of this setting”
 “Subclass this and override these methods
 to customize”
 “Implement something with this interface,
 and register it with the handler”
Bad API design
 “API? Let me see if we have one of
 those...” (AKA: “we don’t”)
 “It’s open source; fork it to do what you
 want” (AKA: “we hate you”)
 def application(environ,
 start_response) (AKA: “we have a
 web service”)
No, really. Your
gateway interface is
   not your API.
4
Build to distribute
So you did the tutorial

 from mysite.polls.models import
 Poll
 mysite.polls.views.vote
 include(‘mysite.polls.urls’)
 mysite.mysite.bork.bork.bork
Project coupling kills
       re-use
Why (some) projects
suck
 You have to replicate that directory
 structure every time you re-use
 Or you have to do gymnastics with your
 Python path
 And you get back into the monolithic
 mindset
A good “project”


 A settings module
 A root URLConf module
 And that’s it.
Advantages

 No assumptions about where things live
 No tricky bits
 Reminds you that it’s just another Python
 module
It doesn’t even have to
    be one module
ljworld.com

 worldonline.settings.ljworld
 worldonline.urls.ljworld
 And a whole bunch of reused apps in
 sensible locations
What reusable apps
look like
 Single module directly on Python path
 (registration, tagging, etc.)
 Related modules under a package
 (ellington.events,
 ellington.podcasts, etc.)
 No project cruft whatsoever
And now it’s easy

 You can build a package with distutils
 or setuptools
 Put it on the Cheese Shop
 People can download and install
General best practices

 Be up-front about dependencies
 Write for Python 2.3 when possible
 Pick a release or pick trunk, and document
 that
 But if you pick trunk, update frequently
Templates are hard

 Providing templates is a big “out of the
 box” win
 But templates are hard to make portable
 (block structure/inheritance, tag libraries,
 etc.)
I usually don’t do
default templates
Either way


 Document template names
 Document template contexts
Be obsessive about
documentation

 It’s Python: give stuff docstrings
 If you do, Django will generate
 documentation for you
 And users will love you forever
“
If the implementation is hard to explain,
 it’s a bad idea. If the implementation is
  easy to explain, it may be a good idea.




                                           ”
                                 -- The Zen of Python
Documentation-driven
development
 Write the docstring before you write the
 code
 Rewrite the docstring before you write the
 code
 And write doctests while you’re at it
Advantages

 You’ll never be lacking documentation
 It’ll be up-to-date
 It’s a lot easier to throw away a docstring
 than to throw away a bunch of code
Django will help you

 Docstrings for views, template tags, etc.
 can use reStructureText formatting
 Plus extra directives for handy cross-
 references to other components you’re
 using
Recap:

 Do one thing, and do it well.
 Don’t be afraid of multiple apps.
 Write for flexibility.
 Build to distribute.
In the beginning...


 There was Django.
 And Ellington.
 And a couple other open-source apps.
...PyCon 2007...


 A few people presented/announced things
 they’d developed
 Sort of a watershed moment
...DjangoCon 2008

 Search for “django” on Google code
 hosting: 848 projects
 djangosites.org lists 1,636 sites
 And those are just the ones we know about
 so far...
“   This is Django’s killer feature.




                                       ”
                                       -- Me
Good examples

 django-tagging (Jonathan Buchanan,
 http://code.google.com/p/django-
 tagging/)
 django-atompub (James Tauber, http://
 code.google.com/p/django-atompub/)
 Search for “django” on code hosting sites
More information
 django-hotclub (http://
 groups.google.com/group/django-
 hotclub/)
 Jannis Leidel’s django-packages (http://
 code.google.com/p/django-
 reusableapps/)
 Django Pluggables: http://
 djangoplugables.com/
Questions?
Photo credits

 quot;Purple Sparkly Pony Ridequot; by ninjapoodles, http://www.flickr.com/photos/ninjapoodles/
 285048576/

 “Stonehenge #2” by severecci, http://www.flickr.com/photos/severecci/129553243/

 “sookiepose” by 416style, http://www.flickr.com/photos/sookie/41561946/

 quot;The Happy Couplequot; by galapogos, http://www.flickr.com/photos/galapogos/343592116/

Contenu connexe

Tendances

SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...Mark Rackley
 
Rey Bango - HTML5: polyfills and shims
Rey Bango -  HTML5: polyfills and shimsRey Bango -  HTML5: polyfills and shims
Rey Bango - HTML5: polyfills and shimsStarTech Conference
 
The Developer Experience
The Developer Experience The Developer Experience
The Developer Experience Pamela Fox
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectureselliando dias
 
Green Lantern Framework with Selenium IDE
Green Lantern Framework with Selenium IDEGreen Lantern Framework with Selenium IDE
Green Lantern Framework with Selenium IDESrilu Balla
 
Java applet basics
Java applet basicsJava applet basics
Java applet basicsSunil Pandey
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedAlexander Makarov
 
API Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterAPI Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterTom Johnson
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02Rich Helton
 
Open Power Template 2 presentation
Open Power Template 2 presentationOpen Power Template 2 presentation
Open Power Template 2 presentationTomasz Jędrzejewski
 
Rich GUI Testing: Swing and JavaFX
Rich GUI Testing: Swing and JavaFXRich GUI Testing: Swing and JavaFX
Rich GUI Testing: Swing and JavaFXAlex Ruiz
 
Survey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a ChatbotSurvey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a ChatbotNguyen Giang
 
Introduction to Selenium and Test Automation
Introduction to Selenium and Test AutomationIntroduction to Selenium and Test Automation
Introduction to Selenium and Test AutomationAhmed Mubbashir Khan
 
Google Developer Day: State of Ajax
Google Developer Day: State of AjaxGoogle Developer Day: State of Ajax
Google Developer Day: State of Ajaxdion
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardJAX London
 
Internal DSLs For Automated Functional Testing
Internal DSLs For Automated Functional TestingInternal DSLs For Automated Functional Testing
Internal DSLs For Automated Functional TestingJohn Sonmez
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Dutyreedmaniac
 
Automated Acceptance Test Practices and Pitfalls
Automated Acceptance Test Practices and PitfallsAutomated Acceptance Test Practices and Pitfalls
Automated Acceptance Test Practices and PitfallsWyn B. Van Devanter
 

Tendances (18)

SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
 
Rey Bango - HTML5: polyfills and shims
Rey Bango -  HTML5: polyfills and shimsRey Bango -  HTML5: polyfills and shims
Rey Bango - HTML5: polyfills and shims
 
The Developer Experience
The Developer Experience The Developer Experience
The Developer Experience
 
Plug-in Architectures
Plug-in ArchitecturesPlug-in Architectures
Plug-in Architectures
 
Green Lantern Framework with Selenium IDE
Green Lantern Framework with Selenium IDEGreen Lantern Framework with Selenium IDE
Green Lantern Framework with Selenium IDE
 
Java applet basics
Java applet basicsJava applet basics
Java applet basics
 
Devconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developedDevconf 2011 - PHP - How Yii framework is developed
Devconf 2011 - PHP - How Yii framework is developed
 
API Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterAPI Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC Chapter
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02
 
Open Power Template 2 presentation
Open Power Template 2 presentationOpen Power Template 2 presentation
Open Power Template 2 presentation
 
Rich GUI Testing: Swing and JavaFX
Rich GUI Testing: Swing and JavaFXRich GUI Testing: Swing and JavaFX
Rich GUI Testing: Swing and JavaFX
 
Survey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a ChatbotSurvey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a Chatbot
 
Introduction to Selenium and Test Automation
Introduction to Selenium and Test AutomationIntroduction to Selenium and Test Automation
Introduction to Selenium and Test Automation
 
Google Developer Day: State of Ajax
Google Developer Day: State of AjaxGoogle Developer Day: State of Ajax
Google Developer Day: State of Ajax
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
 
Internal DSLs For Automated Functional Testing
Internal DSLs For Automated Functional TestingInternal DSLs For Automated Functional Testing
Internal DSLs For Automated Functional Testing
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
Automated Acceptance Test Practices and Pitfalls
Automated Acceptance Test Practices and PitfallsAutomated Acceptance Test Practices and Pitfalls
Automated Acceptance Test Practices and Pitfalls
 

Similaire à Reusable Apps

Pluggable patterns
Pluggable patternsPluggable patterns
Pluggable patternsCorey Oordt
 
BDD with SpecFlow and Selenium
BDD with SpecFlow and SeleniumBDD with SpecFlow and Selenium
BDD with SpecFlow and SeleniumLiraz Shay
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesTikal Knowledge
 
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Chris Laning
 
Immutable Data and TypeScript in an Ember.js Application
Immutable Data and TypeScript in an Ember.js ApplicationImmutable Data and TypeScript in an Ember.js Application
Immutable Data and TypeScript in an Ember.js ApplicationBill Heaton
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Darwin Biler
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsMike Wilcox
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in DjangoLakshman Prasad
 
Introduction to Google App Engine with Python
Introduction to Google App Engine with PythonIntroduction to Google App Engine with Python
Introduction to Google App Engine with PythonBrian Lyttle
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppKaty Slemon
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day trainingTroy Miles
 

Similaire à Reusable Apps (20)

Pluggable patterns
Pluggable patternsPluggable patterns
Pluggable patterns
 
BDD with SpecFlow and Selenium
BDD with SpecFlow and SeleniumBDD with SpecFlow and Selenium
BDD with SpecFlow and Selenium
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 
django
djangodjango
django
 
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
 
Immutable Data and TypeScript in an Ember.js Application
Immutable Data and TypeScript in an Ember.js ApplicationImmutable Data and TypeScript in an Ember.js Application
Immutable Data and TypeScript in an Ember.js Application
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
 
AngularJS best practices
AngularJS best practicesAngularJS best practices
AngularJS best practices
 
Introduce Django
Introduce DjangoIntroduce Django
Introduce Django
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in Django
 
Introduction to Google App Engine with Python
Introduction to Google App Engine with PythonIntroduction to Google App Engine with Python
Introduction to Google App Engine with Python
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Architecting iOS Project
Architecting iOS ProjectArchitecting iOS Project
Architecting iOS Project
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
 
Django - basics
Django - basicsDjango - basics
Django - basics
 

Plus de DjangoCon2008

Plus de DjangoCon2008 (6)

Why I Hate Django
Why I Hate DjangoWhy I Hate Django
Why I Hate Django
 
Pinax
PinaxPinax
Pinax
 
Satchmo
SatchmoSatchmo
Satchmo
 
What’S New In Newforms Admin
What’S New In Newforms AdminWhat’S New In Newforms Admin
What’S New In Newforms Admin
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 

Dernier

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
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
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
[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
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
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
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
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
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Dernier (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
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
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
[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
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
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
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
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
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Reusable Apps

  • 1. Writing reusable applications James Bennett DjangoCon, Mountain View, CA, September 6, 2008
  • 3. The fourfold path Do one thing, and do it well. Don’t be afraid of multiple apps. Write for flexibility. Build to distribute.
  • 4. 1
  • 5. Do one thing, and do it well. ” -- The UNIX philosophy
  • 7. Keep a tight focus Ask yourself: “What does this application do?” Answer should be one or two short sentences
  • 8. Good focus “Handle storage of users and authentication of their identities.” “Allow content to be tagged, del.icio.us style, with querying by tags.” “Handle entries in a weblog.”
  • 9. Bad focus “Handle entries in a weblog, and users who post them, and their authentication, and tagging and categorization, and some flat pages for static content, and...” The coding equivalent of a run-on sentence
  • 10. Warning signs A lot of very good Django applications are very small: just a few files If your app is getting big enough to need lots of things split up into lots of modules, it may be time to step back and re-evaluate
  • 11. Warning signs Even a lot of “simple” Django sites commonly have a dozen or more applications in INSTALLED_APPS If you’ve got a complex/feature-packed site and a short application list, it may be time to think hard about how tightly- focused those apps are
  • 12. Case study: user registration
  • 13.
  • 14. Features User fills out form, inactive account created User gets email with link, clicks to activate And that’s it
  • 15. User registration Different sites want different information Different types of users Different signup workflow Etc., etc.
  • 16. Some “simple” things aren’t so simple.
  • 17. Approach features skeptically
  • 18. Should I add this feature? What does the application do? Does this feature have anything to do with that? No? Guess I shouldn’t add it, then.
  • 19. Top feature request in django-registration: User profiles
  • 20. “ What does that have to do with user registration? ”-- Me
  • 21.
  • 23. django-profiles Add profile Edit profile View profile And that’s it.
  • 24.
  • 25. 2
  • 26. Don’t be afraid of multiple apps
  • 27.
  • 28. The monolith mindset The “application” is the whole site Re-use is often an afterthought Tend to develop plugins that hook into the “main” application Or make heavy use of middleware-like concepts
  • 29. The Django mindset Application == some bit of functionality Site == several applications Tend to spin off new applications liberally
  • 30. Django encourages this Instead of one “application”, a list: INSTALLED_APPS Applications live on the Python path, not inside any specific “apps” or “plugins” directory Abstractions like the Site model make you think about this as you develop
  • 31. Should this be its own application? Is it completely unrelated to the app’s focus? Is it orthogonal to whatever else I’m doing? Will I need similar functionality on other sites? Yes? Then I should break it out into a separate application.
  • 32. Unrelated features Feature creep is tempting: “but wouldn’t it be cool if...” But it’s the road to Hell See also: Part 1 of this talk
  • 33. I’ve learned this the hard way
  • 34. djangosnippets.org One application Includes bookmarking features Includes tagging features Includes rating features
  • 35. Should be about four applications
  • 36. So I wrote a book telling people not to do what I did
  • 37. Page 210, in case you were wondering.
  • 38. Orthogonality Means you can change one thing without affecting others Almost always indicates the need for a separate application Example: changing user profile workflow doesn’t affect user signup workflow. Make them two different applications.
  • 39. Reuse Lots of cool features actually aren’t specific to one site See: bookmarking, tagging, rating... Why bring all this crap about code snippets along just to get the extra stuff?
  • 41. I wanted a blog Entries and links Tagging Comments with moderation Contact form “About” page Etc., etc.
  • 42. I ended up with A blog app (entries and links) A third-party tagging app contrib.comments + moderation app A contact-form app contrib.flatpages Etc., etc.
  • 43. Advantages Don’t keep rewriting features Drop things into other sites easily
  • 44. Need a contact form?
  • 45. urlpatterns += (‘’, (r’^contact/’, include(‘contact_form.urls’)), )
  • 48. Site-specific needs Site A wants a contact form that just collects a message. Site B’s marketing department wants a bunch of info. Site C wants to use Akismet to filter automated spam.
  • 49. 3
  • 51.
  • 52. Common sense Sane defaults Easy overrides Don’t set anything in stone
  • 53. Form processing Supply a form class But let people specify their own if they want
  • 54. class SomeForm(forms.Form): ... def process_form(request, form_class=SomeForm): if request.method == ‘POST’: form = form_class(request.POST) ... else: form = form_class() ...
  • 55. Templates Specify a default template But let people specify their own if they want
  • 56. def process_form(request, form_class=SomeForm, template_name=’do_form.html’): ... return render_to_response(template_name, ...
  • 57. Form processing You want to redirect after successful submission Supply a default URL But let people specify their own if they want
  • 58. def process_form(request, form_class=SomeForm, template_name=’do_form.html’, success_url=’/foo/’): ... return HttpResponseRedirect(success_url)
  • 59. URL best practices Provide a URLConf in the application Use named URL patterns Use reverse lookups: reverse(), permalink, {% url %}
  • 60. Working with models Whenever possible, avoid hard-coding a model class Use get_model() and take an app label/ model name string instead Don’t rely on objects; use the default manager
  • 61. from django.db.models import get_model def get_object(model_str, pk): model = get_model(*model_str.split(‘.’)) return model._default_manager.get(pk=pk) user_12 = get_object(‘auth.user’, 12)
  • 62. Working with models Don’t hard-code fields or table names; introspect the model to get those Accept lookup arguments you can pass straight through to the database API
  • 63. Learn to love managers Managers are easy to reuse. Managers are easy to subclass and customize. Managers let you encapsulate patterns of behavior behind a nice API.
  • 64. Advanced techniques Encourage subclassing and use of subclasses Provide a standard interface people can implement in place of your default implementation Use a registry (like the admin)
  • 65. The API your application exposes is just as important as the design of the sites you’ll use it in.
  • 66. In fact, it’s more important.
  • 67. Good API design “Pass in a value for this argument to change the behavior” “Change the value of this setting” “Subclass this and override these methods to customize” “Implement something with this interface, and register it with the handler”
  • 68. Bad API design “API? Let me see if we have one of those...” (AKA: “we don’t”) “It’s open source; fork it to do what you want” (AKA: “we hate you”) def application(environ, start_response) (AKA: “we have a web service”)
  • 69. No, really. Your gateway interface is not your API.
  • 70. 4
  • 72. So you did the tutorial from mysite.polls.models import Poll mysite.polls.views.vote include(‘mysite.polls.urls’) mysite.mysite.bork.bork.bork
  • 74.
  • 75. Why (some) projects suck You have to replicate that directory structure every time you re-use Or you have to do gymnastics with your Python path And you get back into the monolithic mindset
  • 76. A good “project” A settings module A root URLConf module And that’s it.
  • 77. Advantages No assumptions about where things live No tricky bits Reminds you that it’s just another Python module
  • 78. It doesn’t even have to be one module
  • 79. ljworld.com worldonline.settings.ljworld worldonline.urls.ljworld And a whole bunch of reused apps in sensible locations
  • 80. What reusable apps look like Single module directly on Python path (registration, tagging, etc.) Related modules under a package (ellington.events, ellington.podcasts, etc.) No project cruft whatsoever
  • 81. And now it’s easy You can build a package with distutils or setuptools Put it on the Cheese Shop People can download and install
  • 82. General best practices Be up-front about dependencies Write for Python 2.3 when possible Pick a release or pick trunk, and document that But if you pick trunk, update frequently
  • 83. Templates are hard Providing templates is a big “out of the box” win But templates are hard to make portable (block structure/inheritance, tag libraries, etc.)
  • 84. I usually don’t do default templates
  • 85. Either way Document template names Document template contexts
  • 86. Be obsessive about documentation It’s Python: give stuff docstrings If you do, Django will generate documentation for you And users will love you forever
  • 87. “ If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea. ” -- The Zen of Python
  • 88. Documentation-driven development Write the docstring before you write the code Rewrite the docstring before you write the code And write doctests while you’re at it
  • 89. Advantages You’ll never be lacking documentation It’ll be up-to-date It’s a lot easier to throw away a docstring than to throw away a bunch of code
  • 90. Django will help you Docstrings for views, template tags, etc. can use reStructureText formatting Plus extra directives for handy cross- references to other components you’re using
  • 91. Recap: Do one thing, and do it well. Don’t be afraid of multiple apps. Write for flexibility. Build to distribute.
  • 92. In the beginning... There was Django. And Ellington. And a couple other open-source apps.
  • 93. ...PyCon 2007... A few people presented/announced things they’d developed Sort of a watershed moment
  • 94. ...DjangoCon 2008 Search for “django” on Google code hosting: 848 projects djangosites.org lists 1,636 sites And those are just the ones we know about so far...
  • 95. This is Django’s killer feature. ” -- Me
  • 96. Good examples django-tagging (Jonathan Buchanan, http://code.google.com/p/django- tagging/) django-atompub (James Tauber, http:// code.google.com/p/django-atompub/) Search for “django” on code hosting sites
  • 97. More information django-hotclub (http:// groups.google.com/group/django- hotclub/) Jannis Leidel’s django-packages (http:// code.google.com/p/django- reusableapps/) Django Pluggables: http:// djangoplugables.com/
  • 99. Photo credits quot;Purple Sparkly Pony Ridequot; by ninjapoodles, http://www.flickr.com/photos/ninjapoodles/ 285048576/ “Stonehenge #2” by severecci, http://www.flickr.com/photos/severecci/129553243/ “sookiepose” by 416style, http://www.flickr.com/photos/sookie/41561946/ quot;The Happy Couplequot; by galapogos, http://www.flickr.com/photos/galapogos/343592116/