Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 91 lines (60 sloc) 2.376 kb

Step 01: Most Basic Resource: Site Root

To remove some mystery about traversal, we start with the smallest possible step: an object at the top of our URL space. This object acts as the "root" and has a view which shows some data on that object.

Goals

  • Take a tiny step into traversal
  • Show how Pyramid grabs a resource object and makes it available in a view

Objectives

  • Make a factory for the root object
  • Pass it to the configurator
  • Have a view which displays an attribute on that object

Steps

  1. $ cd ../../resources; mkdir step01; cd step01

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

    System Message: ERROR/3 (<string>, line 33)

    Unknown directive type "literalinclude".

    .. literalinclude:: application.py
       :linenos:
    
    
  3. Copy the following into step01/views.py:

    System Message: ERROR/3 (<string>, line 38)

    Unknown directive type "literalinclude".

    .. literalinclude:: views.py
       :linenos:
    
    
  4. Copy the following into step01/resources.py:

    System Message: ERROR/3 (<string>, line 43)

    Unknown directive type "literalinclude".

    .. literalinclude:: resources.py
       :linenos:
    
    
  5. Copy the following into step01/tests.py:

    System Message: ERROR/3 (<string>, line 48)

    Unknown directive type "literalinclude".

    .. literalinclude:: tests.py
       :linenos:
    
    
  6. $ nosetests should report running 2 tests.

  7. $ python application.py

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

Extra Credit

  1. Is the root factory called once on startup, or on every request? Do a small change that answers this. What is the impact of the answer on this?

Analysis

Our application.py has a small but important change: we create the configuration with a root factory. Our root factory is a simple function that populates.

We put our resource objects in resources.py. Here we make the classes that model our application. We then have a bootstrap.py function which makes an instance of our class and hands back as the top of the tree.

In this step, our tree has one object: the root. It is an instance of SiteFolder. Since it is the root, it doesn't need a __name__ (aka id) nor a __parent__ (reference to the container an object is in.)

Our site_view is passed, by Pyramid, the instance of this folder as context. The view can then grab attributes and other data from the object that is the focus of the URL.

Discussion

  • The concept of factories and their genesis going back to Zope and CMF
  • Pyramid and need for, and management of, __name__ and __parent__
Something went wrong with that request. Please try again.