Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Better Django Views

Alec Koumjian
June 26, 2013
87

Better Django Views

A short look at good and bad patterns in Django Views

Alec Koumjian

June 26, 2013
Tweet

Transcript

  1. A GOOD VIEW 1. Encapsulates the Request / Response Cycle

    2. Composed of Reuseable Bits (DRY) 3. Easy to Debug & Modify http://wallpaperswide.com/kitzbuhel_mountain_view_austria_europe-wallpapers.html Wednesday, June 26, 13
  2. • Obscure the Request / Response Cycle • Not particularly

    Reuseable / DRY • Hard to Debug and Harder to Modify Generic Views == Bad Patterns Wednesday, June 26, 13
  3. An Example: UpdateView Look for post() in inherited Classes Okay,

    what’s super calling? It’s somewhere... in here: Wednesday, June 26, 13
  4. An Example: UpdateView To modify, we have to copy each

    parent function and insert into our override method Wednesday, June 26, 13
  5. A GOOD VIEW 1. Encapsulates the Request / Response Cycle

    2. Composed of Reuseable Bits (DRY) 3. Easy to Debug & Modify http://wallpaperswide.com/kitzbuhel_mountain_view_austria_europe-wallpapers.html Wednesday, June 26, 13
  6. Option 1: Better CBV Write your methods to be atomic

    Always return your response in top level method Wednesday, June 26, 13
  7. Option 2: Pipeline Views I wanted to take things a

    step further. * Easy to debug any point of the request / response cycle * Easy to insert, update, change the order of operations * Reuse lots of pre-made methods without inheritance / mixin hell Wednesday, June 26, 13
  8. Option 2: Pipeline Views How do you dispatch? Pub/Sub Uses

    subscription helpers to perform or skip different operations In this case, process_form will only be run if our request is a PUT or POST Wednesday, June 26, 13
  9. Option 2: Pipeline Views Advantages: * Explicit (better than implicit)

    * Insert logic anywhere into request / response cycle * Very easy to debug, inspect args/kwargs/context between each method * Encourages modular design Disadvantages: * Verbose. Must specify entire pipeline if changing anything from parent * Subscription based dispatching can be complex and confusing * Not really sure if I like it yet Wednesday, June 26, 13
  10. Option 2: Pipeline Views Prototype Pipeline Views Available At: https://github.com/akoumjian/django-conduit

    Very Helpful Site for Generic Views (good luck) http://ccbv.co.uk/ Thanks! Wednesday, June 26, 13