2: Packaging for the Wiki Tutorial Application

Most modern Python development is done using Python packages, an approach Pyramid puts to good use. In this step, we start writing our Wiki application as a standard Python package.

Objectives

  • Get a minimum Python package in place by making a setup.py
  • Get our basic directory structure in place
  • Install our tutorial package

Steps

  1. Use the previous step as the basis for this step:

    (env33)$ cd ..; mkdir step02; cd step02
    
  2. In setup.py, enter the following:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    from setuptools import setup
    
    requires = [
        'pyramid',
    ]
    
    setup(name='tutorial',
          entry_points="""\
          [paste.app_factory]
          main = tutorial:main
          """,
    )
    
  3. Make the new package installed for development then make a directory for the actual code:

    (env33)$ python3.3 setup.py develop
    (env33)$ mkdir tutorial
    
  4. Enter the following into tutorial/__init__.py:

    # package
    
  5. Enter the following into tutorial/wikiapp.py:

    from wsgiref.simple_server import make_server
    from pyramid.config import Configurator
    
    def main():
        config = Configurator()
        config.add_route('hello', '/')
        config.scan('views')
        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()
    
  6. Enter the following into tutorial/views.py:

    from pyramid.response import Response
    from pyramid.view import view_config
    
    @view_config(route_name='hello')
    def hello_world(request):
        return Response('Hello')
    
  7. Run the WSGI application with:

    (env33)$ python3.3 tutorial/wikiapp.py
    
  8. Open http://127.0.0.1:6547/ in your browser.

Analysis

In this case we have a Python package called tutorial. We use the same name in each step of the Wiki tutorial, to avoid unnecessary re-typing.

We moved our views out to a second file views.py. We then told the Configurator to go scan for anything that looks like a configuration instruction, such as the @view_config decorator.

Extra Credit

  1. Why do we make an extra hop in the directory with tutorial?
  2. Could we have eliminated wikiapp.py and put the WSGI application startup in __init__.py? How would that have affected the command used to start the application?
  3. The previous example used config.add_view. This example uses a @view_config decorator. Does Pyramid treat the imperative (add_view) configuration differently than the declarative (@view_config) approach?

Table Of Contents