5: Adding Resources To Hierarchies

Multiple views per type allowing addition of content anywhere in a resource tree.

Background

We now have multiple kinds of things, but only one view per resource type. We need the ability to add things to containers, then view and edit resources.

We will use the previously mentioned concept of named views. A name is a part of the URL that appears after the resource identifier. For example:

@view_config(context=Folder, name='add_document')

...means that this URL:

http://localhost:6543/some_folder/add_document

...will match the view being configured. It's as if you have an object-oriented web with operations on resources represented by a URL.

Goals

  • Allow adding and editing content in a resource tree.
  • Create a simple form which POSTs data.
  • Create a view which takes the POST data, creates a resource, and redirects to the newly-added resource.
  • Create per-type named views.

Steps

  1. We are going to use the previous step as our starting point:

    $ cd ..; cp -r typeviews addcontent; cd addcontent
    $ $VENV/bin/python setup.py develop
    
  2. Our views in addcontent/tutorial/views.py need type-specific registrations:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    from random import randint
    
    from pyramid.httpexceptions import HTTPFound
    from pyramid.location import lineage
    from pyramid.view import view_config
    
    from .resources import (
        Root,
        Folder,
        Document
        )
    
    
    class TutorialViews(object):
        def __init__(self, context, request):
            self.context = context
            self.request = request
            self.parents = reversed(list(lineage(context)))
    
        @view_config(renderer='templates/root.jinja2',
                     context=Root)
        def root(self):
            page_title = 'Quick Tutorial: Root'
            return dict(page_title=page_title)
    
        @view_config(renderer='templates/folder.jinja2',
                     context=Folder)
        def folder(self):
            page_title = 'Quick Tutorial: Folder'
            return dict(page_title=page_title)
    
        @view_config(name='add_folder', context=Folder)
        def add_folder(self):
            # Make a new Folder
            title = self.request.POST['folder_title']
            name = str(randint(0, 999999))
            new_folder = Folder(name, self.context, title)
            self.context[name] = new_folder
    
            # Redirect to the new folder
            url = self.request.resource_url(new_folder)
            return HTTPFound(location=url)
    
        @view_config(name='add_document', context=Folder)
        def add_document(self):
            # Make a new Document
            title = self.request.POST['document_title']
            name = str(randint(0, 999999))
            new_document = Document(name, self.context, title)
            self.context[name] = new_document
    
            # Redirect to the new document
            url = self.request.resource_url(new_document)
            return HTTPFound(location=url)
    
        @view_config(renderer='templates/document.jinja2',
                     context=Document)
        def document(self):
            page_title = 'Quick Tutorial: Document'
            return dict(page_title=page_title)
    
  3. Make a re-usable snippet in addcontent/tutorial/templates/addform.jinja2 for adding content:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <p>
        <form class="form-inline"
              action="{{ request.resource_url(context, 'add_folder') }}"
              method="POST">
            <div class="form-group">
                <input class="form-control" name="folder_title"
                       placeholder="New folder title..."/>
            </div>
            <input type="submit" class="btn" value="Add Folder"/>
        </form>
    </p>
    <p>
        <form class="form-inline"
              action="{{ request.resource_url(context, 'add_document') }}"
              method="POST">
            <div class="form-group">
                <input class="form-control" name="document_title"
                       placeholder="New document title..."/>
            </div>
            <input type="submit" class="btn" value="Add Document"/>
        </form>
    </p>
    
  4. Add this snippet to addcontent/tutorial/templates/root.jinja2:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    {% extends "templates/layout.jinja2" %}
    {% block content %}
    
        <h2>{{ context.title }}</h2>
        <p>The root might have some other text.</p>
        {% include "templates/contents.jinja2" %}
    
        {% include "templates/addform.jinja2" %}
    
    {% endblock content %}
    
  5. Forms are needed in addcontent/tutorial/templates/folder.jinja2:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    {% extends "templates/layout.jinja2" %}
    {% block content %}
    
        <h2>{{ context.title }}</h2>
        {% include "templates/contents.jinja2" %}
    
        {% include "templates/addform.jinja2" %}
    
    {% endblock content %}
    
  6. $ $VENV/bin/nosetests should report running 4 tests.

  7. Run your Pyramid application with:

    $ $VENV/bin/pserve development.ini --reload
    
  8. Open http://localhost:6543/ in your browser.

Analysis

Our views now represent a richer system, where form data can be processed to modify content in the tree. We do this by attaching named views to resource types, giving them a natural system for object-oriented operations.

To mimic uniqueness, we randomly choose a satisfactorily large number. For true uniqueness, we would also need to check that the number does not already exist at the same level of the resource tree.

We'll start to address a couple of issues brought up in the Extra Credit below in the next step of this tutorial, 6: Storing Resources In ZODB.

Extra Credit

  1. What happens if you add folders and documents, then restart your app?
  2. What happens if you remove the pseudo-random, pseudo-unique naming convention and replace it with a fixed value?