The colors of MVC
What is MVC?
● An amazing pattern that can be found
  throughout just about any software
● Controller -> input
● Model -> throughput
● View -> output
● MVP/MVA/etc. are all MVC, just with
  different names
● Not a design pattern
Atomic elements of an application


                            Controller




                    Model

             View
MVC Colorwheel

                        Model



       Cache
                                                   Input
                                                Middleware



               View                Controller


                       Output
                      Middleware
Model
● Raw data comes in, raw data goes out
● App specific code
● Not just storage, all business logic goes in
  the model
● Can be reused across any controller
● Represents what computers want to give to
  users
Controller
● Data transport
● Non app-specific, common across any app
● Http / request / response / headers / ip
  address / cookies / etc.
● Represents link between human and
  computer
Views
● Takes in raw data, returns 'visualized' data
● HTML, XML, JSON, JPEG
● Represents what humans want from the
  cmputer
Controller -> model -> view ->
controller
def new_blog(request):
  # {'author': 'bob', 'title': 'Title', 'body': 'Body'}
  data = request.POST
  blog = Blog.objects.create(**data)
  html = render({'blog': blog}, 'blog.html')
  return HttpResponse(html)
curl -d "title='my blog'&author=bob&body='my blog body'" http://myblog.com/new_blog

                                                                     HTML minify


              HttpRedirect("http://myblog.com/view/%d" % blog.id))




                   Blog.objects.create()




                                            "http://myblog.com/view/%d" % blog.id




python manage.py new_blog --title='My blog' --author="bob" --body="my blog body"
Input Middleware
●   Mix between Controller and Model
●   Processes the data stream from controller
●   Examples: Authentication middleware
●   View hs no idea about Input Middleware
Session Middleware
def session_middleware(request):
  sid = request.COOKIES.get('session_id')
  if sid:
      session = Session.objects.get(id=sid)
  else:
      session = Session.objects.create(**)

  request.session = session
  return request
Output Middleware
● Modifies the data stream from the controller
  after the view
● Examples: HTTP minify middleware
● Completely hidden from the model
HTML Minifier
def minify_middleware(response):
  if 'html' in response.mimetype:
      minified = response.content.replace(' ', '')
      response.content = minified
      return response
  else:
      return response
Cache
● Short circuit of Model and View
● Performance improvement when you can get
  away with returning pre-rendered data+html
● Primary usage of key/value stores
● Performance comes with a price, cache
  invalidation is tough
Cache
def view_blog(request, id):
  key = "html_blog_%s" % id
  html = memcache.get(key)
  if html:
      return html
  else:
      blog = Blog.objects.get(id=id)
      html = render('blog.html', blog)
      return memcache.set(html, key)
curl http://myblog.com/view/45

                                                                     HTML minify


                     render("blog.html", blog)




                   Blog.objects.get()




                                        "%sn%sn%s" % (blog.title, blog.author, blog.body)




python manage.py view_blog 5
MVC is everywhere!
                                                   Blog.objects.get




        def get(self, id):
          table_name = 'blog'
          engine = settings.DB_ENGINE
          q = "select * from %s where id=%s" % (
             table_name, id
          )
          data = engine.execute(q)
          return Blog(**data)
I mean, everywhere!
                                                       render()




         def render(template, context, unicode=True)
           t = open(template).read()
           html = do_render(t, context)
           if unicode:
               return unicode(html)
           else:
               return html
Try not to mix colors
● Keep model code isolated from controller
  and view code
● Coupling is bad
● Reusability, discoverability, and predictability
● If you have to mix colors, its OK! Just
  remember to fix it later!
Giotto
● Application framework that does away with
  controllers
● Not at all like django/pyramid/flask
● Completely decoupled models and views
● https://github.com/priestc/giotto
Giotto example
class Multiply(GiottoProgram)
   name = 'multiply'
   controllers = ('http-get', 'cmd', 'irc')
   model = [multiply]
   view = RedBlueMultiplyViewer
Decoupled Design
                                                                                   Model
                                                                              Postgres, rabbitmq,
                                                                              validation, algorithms
                                                                              facebook api, etc.

                                                       5})
                                                  'y':
                                        ':   3,
                               ',   {'x
                             ly
                       ultip                                                                       {{'x': 3, 'y': 5, 'result': 15}
                    ('m

  HTTP
headers, cookies,
request, ips,
response...            {'body': '<
                                             html...', 'm
                                                             imetype':
                                                                                            View
                                                                         '...' }
                                                                                         HTML, JSON,
                                                                                         mimetypes, image
                                                                                         formats, templates
./giotto http-dev
Decoupled Design
                                                                                   Model
                                                                               Postgres, rabbitmq,
                                                                               validation, algorithms
                                                                               facebook api, etc.

                                                       5})
                                                  'y':
                                        ':   3,
                               ',   {'x
                             ly
                       ultip                                                                        {{'x': 3, 'y': 5, 'result': 15}
                    ('m

  IRC
channels, private
message, server,
ops, voice, etc.       {'body': 't
                                             ext', 'mim
                                                             etype': '.
                                                                                             View
                                                                       ..' }
                                                                                          HTML, JSON,
                                                                                          mimetypes, image
                                                                                          formats, templates
Command Line
Giotto example
class Multiply(GiottoProgram)
   name = 'multiply'
   controllers = ('http-get', 'cmd', 'irc')
   model = [multiply]
   cache = 3600
   view = RedBlueMultiplyViewer
Automatic Cache
                                                                   Model
                                                             Postgres, rabbitmq,
                                                             validation, algorithms
                                                             facebook api, etc.




                                                             {{'x': 3, 'y': 5, 'result': 15}
             ('multiply', {'x': 3, 'y': 5})
Controller                                           Cache
              {'body': 'text', 'mimetype': '...' }


                                                                  View
                                                               HTML, JSON,
                                                               mimetypes, image
                                                               formats, templates
Model Mocking
class Multiply(GiottoProgram)
   name = 'multiply'
   controllers = ('http-get', 'cmd', 'irc')
   model = [multiply, {'x': 10, 'y': 11, 'result':
110}]
   cache = 3600
   view = RedBlueMultiplyViewer
Decoupled Design                                                                                     Model
                                                                                                Postgres, rabbitmq,
                                                                                                validation, algorithms
                                                                                                facebook api, etc.



                                                                               Mock



                                                     5})                   {{'x': 10, 'y': 11, 'result': 110}
                                                'y':
                                           3,
                                     x':
                             ly', {'
                         ltip
                    (' mu

  IRC
channels, private
message, server,
ops, voice, etc.        {'body': 't
                                   ext', 'mim
                                                         etype': '.
                                                                                          View
                                                                   ..' }
                                                                                       HTML, JSON,
                                                                                       mimetypes, image
                                                                                       formats, templates
Model Mocking
● Designers don't need to run
  rabbitmq/postgres/etc.
● Data interchange between model/view is
  explicit and simply stated
Middleware
class Multiply(GiottoProgram)
   name = 'multiply'
   controllers = ('http-get', 'cmd', 'irc')
   input_middleware = [AuthMiddleware]
   model = [multiply]
   cache = 3600
   view = RedBlueMultiplyViewer
   output_middleware = [MinifyMiddleware]
Questions?

Visualizing MVC, and an introduction to Giotto

  • 1.
  • 2.
    What is MVC? ●An amazing pattern that can be found throughout just about any software ● Controller -> input ● Model -> throughput ● View -> output ● MVP/MVA/etc. are all MVC, just with different names ● Not a design pattern
  • 3.
    Atomic elements ofan application Controller Model View
  • 4.
    MVC Colorwheel Model Cache Input Middleware View Controller Output Middleware
  • 5.
    Model ● Raw datacomes in, raw data goes out ● App specific code ● Not just storage, all business logic goes in the model ● Can be reused across any controller ● Represents what computers want to give to users
  • 6.
    Controller ● Data transport ●Non app-specific, common across any app ● Http / request / response / headers / ip address / cookies / etc. ● Represents link between human and computer
  • 7.
    Views ● Takes inraw data, returns 'visualized' data ● HTML, XML, JSON, JPEG ● Represents what humans want from the cmputer
  • 8.
    Controller -> model-> view -> controller def new_blog(request): # {'author': 'bob', 'title': 'Title', 'body': 'Body'} data = request.POST blog = Blog.objects.create(**data) html = render({'blog': blog}, 'blog.html') return HttpResponse(html)
  • 9.
    curl -d "title='myblog'&author=bob&body='my blog body'" http://myblog.com/new_blog HTML minify HttpRedirect("http://myblog.com/view/%d" % blog.id)) Blog.objects.create() "http://myblog.com/view/%d" % blog.id python manage.py new_blog --title='My blog' --author="bob" --body="my blog body"
  • 10.
    Input Middleware ● Mix between Controller and Model ● Processes the data stream from controller ● Examples: Authentication middleware ● View hs no idea about Input Middleware
  • 11.
    Session Middleware def session_middleware(request): sid = request.COOKIES.get('session_id') if sid: session = Session.objects.get(id=sid) else: session = Session.objects.create(**) request.session = session return request
  • 12.
    Output Middleware ● Modifiesthe data stream from the controller after the view ● Examples: HTTP minify middleware ● Completely hidden from the model
  • 13.
    HTML Minifier def minify_middleware(response): if 'html' in response.mimetype: minified = response.content.replace(' ', '') response.content = minified return response else: return response
  • 14.
    Cache ● Short circuitof Model and View ● Performance improvement when you can get away with returning pre-rendered data+html ● Primary usage of key/value stores ● Performance comes with a price, cache invalidation is tough
  • 15.
    Cache def view_blog(request, id): key = "html_blog_%s" % id html = memcache.get(key) if html: return html else: blog = Blog.objects.get(id=id) html = render('blog.html', blog) return memcache.set(html, key)
  • 16.
    curl http://myblog.com/view/45 HTML minify render("blog.html", blog) Blog.objects.get() "%sn%sn%s" % (blog.title, blog.author, blog.body) python manage.py view_blog 5
  • 17.
    MVC is everywhere! Blog.objects.get def get(self, id): table_name = 'blog' engine = settings.DB_ENGINE q = "select * from %s where id=%s" % ( table_name, id ) data = engine.execute(q) return Blog(**data)
  • 18.
    I mean, everywhere! render() def render(template, context, unicode=True) t = open(template).read() html = do_render(t, context) if unicode: return unicode(html) else: return html
  • 19.
    Try not tomix colors ● Keep model code isolated from controller and view code ● Coupling is bad ● Reusability, discoverability, and predictability ● If you have to mix colors, its OK! Just remember to fix it later!
  • 20.
    Giotto ● Application frameworkthat does away with controllers ● Not at all like django/pyramid/flask ● Completely decoupled models and views ● https://github.com/priestc/giotto
  • 21.
    Giotto example class Multiply(GiottoProgram) name = 'multiply' controllers = ('http-get', 'cmd', 'irc') model = [multiply] view = RedBlueMultiplyViewer
  • 22.
    Decoupled Design Model Postgres, rabbitmq, validation, algorithms facebook api, etc. 5}) 'y': ': 3, ', {'x ly ultip {{'x': 3, 'y': 5, 'result': 15} ('m HTTP headers, cookies, request, ips, response... {'body': '< html...', 'm imetype': View '...' } HTML, JSON, mimetypes, image formats, templates
  • 23.
  • 24.
    Decoupled Design Model Postgres, rabbitmq, validation, algorithms facebook api, etc. 5}) 'y': ': 3, ', {'x ly ultip {{'x': 3, 'y': 5, 'result': 15} ('m IRC channels, private message, server, ops, voice, etc. {'body': 't ext', 'mim etype': '. View ..' } HTML, JSON, mimetypes, image formats, templates
  • 25.
  • 26.
    Giotto example class Multiply(GiottoProgram) name = 'multiply' controllers = ('http-get', 'cmd', 'irc') model = [multiply] cache = 3600 view = RedBlueMultiplyViewer
  • 27.
    Automatic Cache Model Postgres, rabbitmq, validation, algorithms facebook api, etc. {{'x': 3, 'y': 5, 'result': 15} ('multiply', {'x': 3, 'y': 5}) Controller Cache {'body': 'text', 'mimetype': '...' } View HTML, JSON, mimetypes, image formats, templates
  • 28.
    Model Mocking class Multiply(GiottoProgram) name = 'multiply' controllers = ('http-get', 'cmd', 'irc') model = [multiply, {'x': 10, 'y': 11, 'result': 110}] cache = 3600 view = RedBlueMultiplyViewer
  • 29.
    Decoupled Design Model Postgres, rabbitmq, validation, algorithms facebook api, etc. Mock 5}) {{'x': 10, 'y': 11, 'result': 110} 'y': 3, x': ly', {' ltip (' mu IRC channels, private message, server, ops, voice, etc. {'body': 't ext', 'mim etype': '. View ..' } HTML, JSON, mimetypes, image formats, templates
  • 30.
    Model Mocking ● Designersdon't need to run rabbitmq/postgres/etc. ● Data interchange between model/view is explicit and simply stated
  • 31.
    Middleware class Multiply(GiottoProgram) name = 'multiply' controllers = ('http-get', 'cmd', 'irc') input_middleware = [AuthMiddleware] model = [multiply] cache = 3600 view = RedBlueMultiplyViewer output_middleware = [MinifyMiddleware]
  • 32.