Step 01: Hello World in Pyramid

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

Goals

  • Get Pyramid pixels on the screen as easily as possible
  • Use that as a well-understood base for adding each unit of complexity

Objectives

  • 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. They provide low-overhead on execution. But also, 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 Tutorial Setup.

  2. $ mkdir creatingux; cd creatingux

  3. $ mkdir step01; cd step01

  4. Copy the following into step01/application.py:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    from wsgiref.simple_server import make_server
    
    from pyramid.config import Configurator
    from pyramid.response import Response
    
    # This acts as the view function
    def hello_world(request):
        return Response('hello!')
    
    def main():
        # Grab the config, add a view, and make a WSGI app
        config = Configurator()
        config.add_view(hello_world)
        app = config.make_wsgi_app()
        return app
    
    if __name__ == '__main__':
        # When run from command line, launch a WSGI server and app
        app = main()
        server = make_server('0.0.0.0', 8080, app)
        server.serve_forever()
    
  5. $ python application.py

  6. Open http://127.0.0.1:8080 in your browser.

Extra Credit

  1. What happens if you return a string of HTML? A sequence of integers?
  2. Put something invalid, such as print xyz, in the view function. Kill your python application.py and restart, then reload your browser. See the exception in the console?
  3. Does Pyramid support automatic reloading of Python code?

Analysis

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.

Discussion

  • Background on megaframeworks, microframeworks, and Pyramid’s opinion thereof

Table Of Contents