Intro to Pyramid
Upcoming SlideShare
Loading in...5
×
 

Intro to Pyramid

on

  • 4,913 views

Introduction to Pyramid talk delivered at PyGotham 9/17/11. High level overview of the framework. Comparisons to other web frameworks. Walk through simple blog app with mongoDB. Highlight some ...

Introduction to Pyramid talk delivered at PyGotham 9/17/11. High level overview of the framework. Comparisons to other web frameworks. Walk through simple blog app with mongoDB. Highlight some pitfalls and tips while learning Pyramid.

Statistics

Views

Total Views
4,913
Views on SlideShare
4,519
Embed Views
394

Actions

Likes
4
Downloads
65
Comments
0

6 Embeds 394

http://simple-is-better.com 316
http://lanyrd.com 38
http://feed.feedsky.com 20
http://www.simple-is-better.com 11
http://xianguo.com 5
http://pythontip.sinaapp.com 4

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • -In this talk I'm going to give you a high level overview of Pyramid -Highlight some advantages and disadvantages vs. other frameworks -We'll walk through MongoDB integration with a simple blog app -II'll go over some pitfals i've encountered while learning pyramid -I'll point you at some resources that should help you get started -And finally we'll have plenty of questions - 1. peak your interest enough for you to try it out. 2. provide you with some examples of how to use it 3. Give you tips and point you in the right direction so you can create your own pyramid apps.
  • -Just a little background -I used to work as a software engineer at a financial services company -We had a very large legacy C++ (and some python) code base -It was very hard to maintain and test -You gain an appreciation for good design and tests. I'm sure many of you can relate -So when I decided to start building web apps for fun  about a year ago and while I was looking for a framework; extensible design and and testability were very high on my list. -I tried out django and other web frameworks, but the framework that ended up having the best balance for my needs was Pyramid -So, thats what I ended up running with 
  • -It's primary function is to make it easier to build and maintain web apps -Similar to Django, Rails,  and other web frameworks -But it focuses more on "maintenance" and "flexability" that other web frameworks  -It's general enough that it can be used to build a wide array of apps -Everything from Simple blogs, to intranets, to CMS, and Social platforms.
  • -Around 2004-2005 there was an explosion of web frameworks -Ruby on Rails in 2004, Pylons, TurboGears, Django around 2005 -Then came along Repoze.bfg around 2008, which was influenced by the Zope web frameworks -Then a couple years later Pylons, Repoze, and TG merge into the Pylons project -The Pylons project is a collection of we relaated python projects under a single umbrella (think Apache) -Pylons development was discontinued -Repoze.bfg was re-branded as Pyramid.  thank goodness, because you can't think of a worst name than Repoze.BFG -Now Pyramid is currently the main web framework under the Pylons project
  • -Wont go into too much technical detail, but here's how you would typically start a pyramid project -You would create your virtual environment -Virtualenv, for those of you that are unfamiliar, alows you to create isolated python environments.  Useful, because it prevent conflicts between globally installed and other development packages. -easy or pip install pyramid -Run this create command -It will generate a "scaffold" or template for you to build your app in
  • -Lets look at a very basic  pyramid application -This app will display the text "Hello World!" if you do to localhost:8080/hello/bob -we create a config object -add a route named "hello" that maps to a URL that matches this pattern: /hello/{name} -attach the route to a view callable -which is this function above -This view callable refferences the name variable, passed in via the url and it's appended to the response -When the app is ran, and we go to local host:8080/hello/world -we see hello world in the browser -if we go to localhost:8080/hello/mars Hello Mars is shown in the browser
  • -Not all web apps are equal, they each have different areas of focus -Pyramid focuses on excelling in these following 6 tenets
  • -Let's look into each one of these -Only pay for what you eat -You're not forced to use any particular technology -You add components as you see fit
  • -Pyramid has a relatively small code base -Out of the box it provides only core functionality -This tenet helps it stay fast and flexible, we'll go more into its performance soon
  • -You can see the docs, which include tutorials, cookbooks, etc here -Documentation isn't as abundant as django and other mature frameworks, but it's continuing to improve
  • -not only do the tests cover every line of code, but they are well written -If you want examples of how to write good tests, see the pyramid source code -Their moto is if it aint tested its broken
  • -Pyramid is of cource open souce -And the community is very active -Main developers... -There's also a growing library of pyramid related projects on github
  •   -How fast can we make requests and spit out the hello world string per second -More requests per second the better
  •   -The template test spits out Lorem Ipsum via a template (thus engaging the framework’s templating systems).  
  •   The template/db test: This test loads 5 rows of Lorem Ipsum from a SQLite DB (via the default ORM or a sqlite3 driver) and then prints them out through a template (thus engaging both the framework’s ORM/DB driver and the templating system).
  • Number of lines of profiler output generated by 1000 hits to a hello world application As you can see Pyramid makes significantly less function calls ----- -he "numlines" value above is the number of lines of profiler output generated by 1000 hits to a warm "hello world" application in each framework. This number was taken from the "Profile lines" data point in each "results.txt" of each subdirectory of the reporting data. This metric counts the number of lines output by the Python profiler after these 1000 hits.   -While a lower number doesn't necessarily always mean the system is faster or simpler on every axis, there is often a correlation between the number of profile lines output and the relative complexity and speed of the very core of the system being tested.    -good example of minimalism 
  • -So we've seen how well Pyramid can perform, how well does it do in terms of flexibility -bullet 1 -whatever you think best of breed is -Pyramid does allow you to start projects using scaffolds or pre-canned templates -for example you can use the SQLAlchemy scaffold if you want that ORM to handle your persistant store -New components come out frequently and you can see them being integrated into pyramid on github
  • -The official pymongo API is simple enough and flexible     
  •    
  • -Some of the things I spent way too much time wrestling with where routing methods and template engines
  • -Questlr (without the second e) is what I'm currently working on

Intro to Pyramid Intro to Pyramid Presentation Transcript

  • Intro to Pyramid Building Fast and Flexible Web Apps by Brian Cajes
  • Overview
      • What is Pyramid?
      • Pyramid vs. Other Frameworks
      • MongoDB Integration
      • Some Things I've Learned
      • The Community & Resources
      • Wrap up & Questions
  • My Background
      • Worked as a Software Engineer at a Financial Services Company
        • Large legacy C++ code base
        • Hard to maintain and test
      • Web apps on the side
        • Want flexibility and testability in my web framework
        • Pyramid!
      • Recently quit the finance job
      • Turned side project into start-up 
  • What is Pyramid?
      • An open source web framework
      • Easier to create arbitrary web apps
      • Can be used to build wide array of applications
        • Simple Blogs
        • CMS
        • Social Web Apps
        • ...
  • Brief History
    •  
      • Pylons,TurboGears, Django(2005-)
    •  
      • Repoze.bfg (2008-2010) 
        • Influenced by Zope* (1998?-)
        • Chris Mcdonough
      • Pylons, Repoze.bfg, TG merge into The Pylons Project  (2010)
        • A collection of web related Python projects under a single umbrella   
        • Pylons development discontinued
        • Repoze.bfg renamed to Pyramid
        • Pyramid currently the main web framework
  • Setting up Pyramid
    • $ virtualenv --no-site-packages env 
    • $ cd env 
    • $ bin/easy_install pyramid
    • $ bin/paster create -t pyramid_starter
    •  
  • Hello World
    • from paste.httpserver import serve 
    • from pyramid.config import Configurator 
    • from pyramid.response import Response  
    • def hello_world(request): 
    •      return Response('Hello %(name)s!' %request.matchdict)
    • if __name__ == '__main__': 
    •      config = Configurator() 
    •      config.add_route('hello', '/hello/{name}')
    •     config.add_view(hello_world, route_name='hello') 
    •     app =  config.make_wsgi_app() 
    •     serve(app, host='0.0.0.0')
    •    
    • #serving on 0.0.0.0:8080 view at http://127.0.0.1:8080
    • #url localhost:8080/hello/bob  -> prints 'Hello Bob!' in the browser
    • #full documentation and tutorials: 
    • #https://docs.pylonsproject.org/projects/pyramid/1.2/
  • Pyramid's Tenets
      • Simplicity
    •  
      • Minimalism
    •  
      • Documentation
    •  
      • Reliability
    •  
      • Openness
    •  
      • Speed
    •   *https://www.pylonsproject.org/projects/pyramid/about
  • Simplicity
      • "Only pay for what you eat"
    •  
      •   Not forced to user any particular technology
        • No DB
        • SQL
        • MongoDB
        • All okay
      • Easy to set up basic apps
  • Minimalism
      • Relatively small code base (~5000 lines)
        • Django ~60,000 lines
    •  
      • Concentrates on common core activities: URL mapping, templating, security, and serving static assets
  • Documentation
      • Every aspect of the framework is documented
    •  
      •   https://docs.pylonsproject.org/
    •  
      • Coverage is good, but sometimes lacks good examples
        • Improving over time
    •  
  • Reliability
      • Tested exhaustively
    •  
      • 100% code test coverage
    •  
      • "If it ain’t tested, it’s broke"
    •  
      • Source code has good examples of well written tests
    •  
  • Openness
      • "As with Python, the Pyramid software is distributed under a permissive open source license ."
    •  
      • Active community
        • Main developers Chris McDonough, Ben Bangert, and others respond to question frequently
        • Growing library of open source pyramid related projects
  • Speed
      • Core functionality is optimized for very fast execution
      • Hardware maybe cheap these days
      • The time and energy needed to manage all that hardware is not so cheap
    •  
  • Performance Comparison: String Test
    • *http://blog.curiasolutions.com/the-great-web-framework-shootout/
  • Performance Comparison: Templates
    • *http://blog.curiasolutions.com/the-great-web-framework-shootout/
  • Performance Comparison: Templates + DB Queries
    • *http://blog.curiasolutions.com/the-great-web-framework-shootout/
  • Profiling Comparison
    • Numlines System 22 Pyramid (1.0a9) 34 Bottle (0.8.1) 57 Django (1.02) 96 Flask (0.6) 96 Pylons (0.9.7rc4) 250 Zope2 (2.10 via repoze.zope2) 317 Grok (1.0a1) 398 TurboGears 2 (2.0.3)
    •   *http://plope.com/pyroptimization
  • Component Architecture
      • Advantages of an un-opinionated framework
        • Simplicity
        • Speed out of the box
        • Bring in "best of breed" components as you see fit
      • Start Pyramid projects with pre-canned scaffolds if you want (eg. SQLAlchemy + URL dispatch)
      • Can add components by simply installing python packages
  • Example: MongoDB Integration
      • Let's build a simple blog using Pyramid and MongoDB as the persistent store 
    •  
      • Easy enough to wire up mongoDB manually
        • start here: https://docs.pylonsproject.org/projects/pyramid_cookbook/dev/mongo.html
    •  
      • Or start with existing pyramid_mongodb template (ie. scaffold) by Niall O’Higgins
        •   https://github.com/niallo/pyramid_mongodb
        •   easy_install pyramid_mongodb
        •   $ paster create --list-templates          Available templates:                    pyramid_mongodb:        pyramid MongoDB
  • Example: MongoDB Integration
      • __init__.py : wiring MongoDB to Pyramid
    •  
    • def main(global_config, **settings):
    •      """ This function returns a Pyramid WSGI application.
    • """
    • ...
    •      db_uri = settings['db_uri']
    •      conn = pymongo.Connection(db_uri)
    •      config.registry.settings['db_conn'] = conn
    •      config.add_subscriber(add_mongo_db, NewRequest)
    • ...
    •      return config.make_wsgi_app()
    • def add_mongo_db(event):
    •      settings = event.request.registry.settings
    •      db = settings['db_conn'][settings['db_name']]
    •      event.request.db = db
    •  
    •   * https://github.com/supr/Blog  
    • *
  • Example: MongoDB Integration cont.
      • blog/views.py: making calls to MongoDB
    • @view_config( route_name = "home", renderer = "index.mk" )
    • def home (request):
    •      entries =  request . db . Entries . find({},sort = [("datetime",DESCENDING)]) . limit(4)
    •      return { 'entries':entries }
  • Example: MongoDB Integration cont.
      • snippet from blog/templates/index.mk
    • %for entry in entries:
    • <h2>${entry['title'] | h,trim,unicode }</h2>
    • <p>Posted by ${entry['username'] | h} on ${entry['datetime'].strftime(&quot;%A, %d %B %Y at %I:%M %p&quot;)}</p>
    • <p>${entry['content'] | h,trim,unicode }</p>
    • <p>Tags:${&quot;,&quot;.join(entry['tags'])}</p>
    • %endfor
  • Example: MongoDB Integration cont.
      • blog/templates/new.mk
    • <html>
    •      <head>
    •          <title> New Blog Post </title>
    •      </head>
    •      <body>
    •          <h1> New Post </h1>
    •          <form method=&quot;POST&quot;>
    •          <input type=&quot;text&quot; name=&quot;title&quot;/>
    •          <textarea name=&quot;content&quot;></textarea>
    •          <input type=&quot;text&quot; name=&quot;tags&quot;/>
    •          <input type=&quot;submit&quot; value=&quot;Post&quot;             name=&quot;form.submitted&quot;/>
    •          </form>
    •      </body>
    • </html>
  • Example: MongoDB Integration cont.
    • @view_config( route_name = &quot;new&quot;, renderer = &quot;new.mk&quot;, permission = &quot;new&quot; )
    • def new_entry (request):
    •      message = ''
    •      if 'form.submitted' in request . params:
    •          try :
    •              title = request . params['title']
    •              content = request . params['content']
    •              tags = [ x . strip() for x in request . params['tags'] . split(&quot;,&quot;) ]
    •              username = authenticated_userid(request)
    •              entry = dict(
    •                  title = title,
    •                  content = content,
    •                  tags = tags,
    •                  username = username,
    •                  datetime = datetime . now(),
    •                  )
    •              request . db . Entries . insert(entry)
    •          except :
    •              message = 'Invalid forum parameters'
    •              return dict(
    •                  message = message
    •                  )
    •      return {}
  • Things I've Learned Along the Way
      • MongoDB ORM wrappers aren't needed for most use-cases
        • Pymongo is simple and flexible
        • Easy to use within Pyramid
    •  
      • Nose + Webtest
        • Nose -  python test manager
        • Webtest - utility that helps with testing python web apps
        • They integrate well with pyramid
    •  
  • Things I've Learned Along the Way
      • Pyramid does not force the Model-View-Controller pattern on you
        • Difficult to internalize if you're used to MVC everywhere
        • Free yourself from MVC
        • It's not always the best architecture pattern
      • Choices == power
        • but it can sometimes be overwhelming for beginners
        • Tutorials, examples, and documentation improving
    •  
  • Things I've Learned Along the Way cont.
      • Two methods of routing requests
        • URL Dispatch
          • Simple pattern matching
          •   Maps a view function to a URL pattern
        • Traversal
          • Analogous to opening a file/directory in your OS's file system  
        • Stick with URL Dispatch if you're a beginner
    •  
      • Templating Engine
        • Comes with Chameleon and Mako support
        • I prefer Mako's syntax
    •  
  • Community
      • Community Contributions 
        • Pyramid projects on Github
          • Best way to learn (other than documentation) 
        • Many pyramid_* packages and continuing to grow
    •  
      • Google Groups
        • http://groups.google.com/group/pylons-discuss
    •  
      • IRC: #pylons on Freenode
  • Summary
      • Pyramid is a fast and flexible web framework
      • Beats similar web frameworks in many performance metrics
      • Component Architecture
      • More choices and flexibility can be good in the long run, but maybe overwhelming for beginners at first
      • Learn from and contribute back to the Pylons Community
  • Thanks for listening!
      • Twitter: bcajes
      • Questlr.com
        • Connecting people and real life quests. Share goals, challenges, and stories while inspring others.
        • Beta signups 
    •  
    •  
    •  
    •  
    • Questions?