Edit me on GitHub

1: Single-File WSGI Applications

What’s the simplest way to get started in Pyramid? A single-file module. No packages, setup.py, or other machinery.

Objectives

  • Get Pyramid pixels on the screen as easily as possible
  • Use that as a well-understood base for adding each unit of complexity
  • Create a module with a view that acts as an HTTP server
  • Visit the URL in your browser

Background

Microframeworks are all the rage these days. “Microframework” is a marketing term, not a technical one. They have a low mental overhead: they do so little, the only things you have to worry about are your things.

Pyramid is special because it can act as a single-file module microframework. You have a single Python file that can be executed directly by Python. But Pyramid also scales to the largest of applications.

Steps

  1. Make sure you have followed the steps in Python Setup.

  2. Create a directory for this step:

    (env33)$ mkdir step01; cd step01
    
  3. Copy the following into helloworld.py:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    from wsgiref.simple_server import make_server
    from pyramid.config import Configurator
    from pyramid.response import Response
    
    def hello_world(request):
        return Response('Hello')
    
    def main():
        config = Configurator()
        config.add_route('hello', '/')
        config.add_view(hello_world, route_name='hello')
        app = config.make_wsgi_app()
        return app
    
    if __name__ == '__main__':
        app = main()
        server = make_server('0.0.0.0', 6547, app)
        print ('Starting up server on http://localhost:6547')
        server.serve_forever()
    
  4. Run the application:

    (env33)$ python3.3 helloworld.py
    
  5. Open http://127.0.0.1:6547/ in your browser.

Analysis

The main() function is run from the if at the bottom, which makes a WSGI application, hands it to an HTTP server (the pure-Python server in the Python standard library), and starts listening.

This single-file module does quite a bit for so few lines, thus making it spiritually similar to microframeworks. A view function is added to the configuration. When called, the view returns a response.

The hello_world view is mapped to a route which is matched to the root URL of the application.

Extra Credit

  1. Why do we do this:

    print ('Starting up server on http://localhost:6547')
    

    ...instead of:

    print 'Starting up server on http://localhost:6547'
    
  2. What happens if you return a string of HTML? A sequence of integers?

  3. Put something invalid, such as print xyz, in the view function. Kill your python helloworld.py and restart, then reload your browser. See the exception in the console?

Table Of Contents

Previous topic

Tutorial Approach

Next topic

2: Packaging for the Wiki Tutorial Application