Views in BFG are typically simple Python functions that accept two parameters: context, and request. A view is assumed to return a response object.
We’re going to add four view functions to our views.py module. One view (named view_wiki) will display the wiki itself (it will answer on the root URL), another named view_page will display an individual page, another named add_page will allow a page to be added, and a final view named edit_page will allow a page to be edited.
Note
There is nothing automagically special about the filename views.py. A project may have many views throughout its codebase in arbitrarily-named files. Files implementing views often have view in their filenames (or may live in a Python subpackage of your application package named views), but this is only by convention.
The view_wiki function will respond as the default view of a Wiki model object. It always redirects to the Page object named “FrontPage”. It returns an instance of the webob.exc.HTTPFound class (instances of which implement the WebOb response interface), and the repoze.bfg.model_url API. model_url constructs a URL to the FrontPage page (e.g. http://localhost:6543/FrontPage), and uses it as the “location” of the HTTPFound response, forming an HTTP redirect.
The view_page function will respond as the default view of a Page object. The view_page function renders the ReStructuredText body of a page (stored as the data attribute of the context, which will be a Page object) as HTML. Then it substitutes an HTML anchor for each WikiWord reference in the rendered HTML using a compiled regular expression.
The curried function named check is used as the first argument to wikiwords.sub, indicating that it should be called to provide a value for each WikiWord match found in the content. If the wiki (our page’s __parent__) already contains a page with the matched WikiWord name, the check function generates a view link to be used as the substitution value and returns it. If the wiki does not already contain a page with with the matched WikiWord name, the function generates an “add” link as the substitution value and returns it.
As a result, the content variable is now a fully formed bit of HTML containing various view and add links for WikiWords based on the content of our current page object.
We then generate an edit URL (because it’s easier to do here than in the template), and we call the repoze.bfg.chameleon_zpt.render_template_to_response function with a number of arguments. The first argument is the relative path to a Chameleon ZPT template. It is relative to the directory of the file in which we’re creating the view_page function. The render_template_to_response function also accepts request, page, content, and edit_url as keyword arguments. As a result, the template will be able to use these names to perform various rendering tasks.
The result of render_template_to_response is returned to repoze.bfg. Unsurprisingly, it is a response object.
The add_page function will be invoked when a user clicks on a WikiWord which isn’t yet represented as a page in the system. The check function within the view_page view generates URLs to this view. It also acts as a handler for the form that is generated when we want to add a page object. The context of the add_page view is always a Wiki object (not a Page object).
The request subpath in BFG is the sequence of names that are found after the view name in the URL segments given to BFG as the result of a request. If our add view is invoked via, e.g. http://localhost:6543/add_page/SomeName, the subpath will be ['SomeName'].
The add view takes the zeroth element of the subpath (the wiki page name), and aliases it to the name attribute in order to know the name of the page we’re trying to add.
If the view rendering is not a result of a form submission (if the expression 'form.submitted' in request.params is False), the view renders a template. To do so, it generates a “save url” which the template use as the form post URL during rendering. We’re lazy here, so we’re trying to use the same template (templates/edit.pt) for the add view as well as the page edit view, so we create a dummy Page object in order to satisfy the edit form’s desire to have some page object exposed as page, and we’ll render the template to a response.
If the view rendering is a result of a form submission (if the expression 'form.submitted' in request.params is True), we scrape the page body from the form data, create a Page object using the name in the subpath and the page body, and save it into “our context” (the wiki) using the __setitem__ method of the context. We then redirect back to the view_page view (the default view for a page) for the newly created page.
The edit_page function will be invoked when a user clicks the “Edit this Page” button on the view form. It renders an edit form but it also acts as the handler for the form it renders. The context of the edit_page view will always be a Page object (never a Wiki object).
If the view rendering is not a result of a form submission (if the expression 'form.submitted' in request.params is False), the view simply renders the edit form, passing the request, the page object, and a save_url which will be used as the action of the generated form.
If the view rendering is a result of a form submission (if the expression 'form.submitted' in request.params is True), the view grabs the body element of the request parameter and sets it as the data attribute of the page context. It then redirects to the default view of the context (the page), which will always be the view_page view.
The result of all of our edits to views.py will leave it looking like this:
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 61 62 63 64 65 66 67 68 69 70 71 | from docutils.core import publish_parts
import re
from webob.exc import HTTPFound
from repoze.bfg.url import model_url
from repoze.bfg.chameleon_zpt import render_template_to_response
from repoze.bfg.view import static
from tutorial.models import Page
# regular expression used to find WikiWords
wikiwords = re.compile(r"\b([A-Z]\w+[A-Z]+\w+)")
static_view = static('templates/static')
def view_wiki(context, request):
return HTTPFound(location = model_url(context, request, 'FrontPage'))
def view_page(context, request):
wiki = context.__parent__
def check(match):
word = match.group(1)
if word in wiki:
page = wiki[word]
view_url = model_url(page, request)
return '<a href="%s">%s</a>' % (view_url, word)
else:
add_url = request.application_url + '/add_page/' + word
return '<a href="%s">%s</a>' % (add_url, word)
content = publish_parts(context.data, writer_name='html')['html_body']
content = wikiwords.sub(check, content)
edit_url = model_url(context, request, 'edit_page')
return render_template_to_response('templates/view.pt',
request = request,
page = context,
content = content,
edit_url = edit_url)
def add_page(context, request):
name = request.subpath[0]
if 'form.submitted' in request.params:
body = request.params['body']
page = Page(body)
page.__name__ = name
page.__parent__ = context
context[name] = page
return HTTPFound(location = model_url(page, request))
save_url = model_url(context, request, 'add_page', name)
page = Page('')
page.__name__ = name
page.__parent__ = context
return render_template_to_response('templates/edit.pt',
request = request,
page = page,
save_url = save_url)
def edit_page(context, request):
if 'form.submitted' in request.params:
context.data = request.params['body']
return HTTPFound(location = model_url(context, request))
return render_template_to_response('templates/edit.pt',
request = request,
page = context,
save_url = model_url(context, request,
'edit_page')
)
|
The views we’ve added all reference a template. Each template is a Chameleon template. The default templating system in repoze.bfg is a variant of ZPT provided by Chameleon. These templates will live in the templates directory of our tutorial package.
The view.pt template is used for viewing a single wiki page. It is used by the view_page view function. It should have a div that is “structure replaced” with the content value provided by the view. It should also have a link on the rendered page that points at the “edit” URL (the URL which invokes the edit_page view for the page being viewed).
Once we’re done with the view.pt template, it will look a lot like the below:
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 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>${page.__name__} - bfg tutorial wiki (based on TurboGears 20-Minute Wiki)</title>
<link rel="stylesheet" type="text/css"
href="${request.application_url}/static/style.css" />
</head>
<body>
<div class="main_content">
<div style="float:right; width: 10em;"> Viewing
<span tal:replace="page.__name__">Page Name Goes Here</span> <br/>
You can return to the <a href="${request.application_url}">FrontPage</a>.
</div>
<div tal:replace="structure content">Page text goes here.</div>
<p><a tal:attributes="href edit_url" href="">Edit this page</a></p>
</div>
</body></html>
|
The edit.pt template is used for adding and editing a wiki page. It is used by the add_page and edit_page view functions. It should display a page containing a form that POSTs back to the “save_url” argument supplied by the view. The form should have a “body” textarea field (the page data), and a submit button that has the name “form.submitted”. The textarea in the form should be filled with any existing page data when it is rendered.
Once we’re done with the edit.pt template, it will look a lot like the below:
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 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>bfg tutorial wiki (based on TurboGears 20-Minute Wiki) Editing: ${page.__name__}</title>
<link rel="stylesheet" type="text/css"
href="${request.application_url}/static/style.css" />
</head>
<body>
<div class="main_content">
<div style="float:right; width: 10em;"> Viewing
<span tal:replace="page.__name__">Page Name Goes Here</span> <br/>
You can return to the <a href="${request.application_url}">FrontPage</a>.
</div>
<div>
<form action="${save_url}" method="post">
<textarea name="body" tal:content="page.data" rows="10" cols="60"/>
<input type="submit" name="form.submitted" value="Save"/>
</form>
</div>
</div>
</body>
</html>
|
Our templates name a single static resource named style.css. We need to create this and place it in a file named style.css within our package’s templates/static directory:
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | html, body {
color: black;
background-color: #ddd;
font: x-small "Lucida Grande", "Lucida Sans Unicode", geneva, verdana, sans-serif;
margin: 0;
padding: 0;
}
td, th {padding:3px;border:none;}
tr th {text-align:left;background-color:#f0f0f0;color:#333;}
tr.odd td {background-color:#edf3fe;}
tr.even td {background-color:#fff;}
#header {
height: 80px;
width: 777px;
background: blue URL('../images/header_inner.png') no-repeat;
border-left: 1px solid #aaa;
border-right: 1px solid #aaa;
margin: 0 auto 0 auto;
}
a.link, a, a.active {
color: #369;
}
#main_content {
color: black;
font-size: 127%;
background-color: white;
width: 757px;
margin: 0 auto 0 auto;
border-left: 1px solid #aaa;
border-right: 1px solid #aaa;
padding: 10px;
}
#sidebar {
border: 1px solid #aaa;
background-color: #eee;
margin: 0.5em;
padding: 1em;
float: right;
width: 200px;
font-size: 88%;
}
#sidebar h2 {
margin-top: 0;
}
#sidebar ul {
margin-left: 1.5em;
padding-left: 0;
}
h1,h2,h3,h4,h5,h6,#getting_started_steps {
font-family: "Century Schoolbook L", Georgia, serif;
font-weight: bold;
}
h2 {
font-size: 150%;
}
#footer {
border: 1px solid #aaa;
border-top: 0px none;
color: #999;
background-color: white;
padding: 10px;
font-size: 80%;
text-align: center;
width: 757px;
margin: 0 auto 1em auto;
}
.code {
font-family: monospace;
}
span.code {
font-weight: bold;
background: #eee;
}
#status_block {
margin: 0 auto 0.5em auto;
padding: 15px 10px 15px 55px;
background: #cec URL('../images/ok.png') left center no-repeat;
border: 1px solid #9c9;
width: 450px;
font-size: 120%;
font-weight: bolder;
}
.notice {
margin: 0.5em auto 0.5em auto;
padding: 15px 10px 15px 55px;
width: 450px;
background: #eef URL('../images/info.png') left center no-repeat;
border: 1px solid #cce;
}
.fielderror {
color: red;
font-weight: bold;
}
|
This CSS file will be accessed via e.g. http://localhost:6543/static/style.css by virtue of the static_view view we’ve defined in the views.py file. Any number and type of static resources can be placed in this directory (or subdirectories) and are just referred to by URL within templates.
We’ll modify our tests.py file, adding tests for each view function we added above. As a result, we’ll delete the ViewTests test in the file, and add four other test classes: ViewWikiTests, ViewPageTests, AddPageTests, and EditPageTests. These test the view_wiki, view_page, add_page, and edit_page views respectively.
Once we’re done with the tests.py module, it will look a lot like the below:
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | import unittest
from repoze.bfg import testing
class PageModelTests(unittest.TestCase):
def _getTargetClass(self):
from tutorial.models import Page
return Page
def _makeOne(self, data=u'some data'):
return self._getTargetClass()(data=data)
def test_constructor(self):
instance = self._makeOne()
self.assertEqual(instance.data, u'some data')
class WikiModelTests(unittest.TestCase):
def _getTargetClass(self):
from tutorial.models import Wiki
return Wiki
def _makeOne(self):
return self._getTargetClass()()
def test_it(self):
wiki = self._makeOne()
self.assertEqual(wiki.__parent__, None)
self.assertEqual(wiki.__name__, None)
class AppmakerTests(unittest.TestCase):
def _callFUT(self, zodb_root):
from tutorial.models import appmaker
return appmaker(zodb_root)
def test_it(self):
root = {}
self._callFUT(root)
self.assertEqual(root['app_root']['FrontPage'].data,
'This is the front page')
class ViewWikiTests(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def test_it(self):
from tutorial.views import view_wiki
context = testing.DummyModel()
request = testing.DummyRequest()
response = view_wiki(context, request)
self.assertEqual(response.location, 'http://example.com/FrontPage')
class ViewPageTests(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _callFUT(self, context, request):
from tutorial.views import view_page
return view_page(context, request)
def test_it(self):
wiki = testing.DummyModel()
wiki['IDoExist'] = testing.DummyModel()
context = testing.DummyModel(data='Hello CruelWorld IDoExist')
context.__parent__ = wiki
context.__name__ = 'thepage'
request = testing.DummyRequest()
renderer = testing.registerDummyRenderer('templates/view.pt')
response = self._callFUT(context, request)
self.assertEqual(renderer.request, request)
self.assertEqual(
renderer.content,
'<div class="document">\n'
'<p>Hello <a href="http://example.com/add_page/CruelWorld">'
'CruelWorld</a> '
'<a href="http://example.com/IDoExist/">'
'IDoExist</a>'
'</p>\n</div>\n')
self.assertEqual(renderer.edit_url,
'http://example.com/thepage/edit_page')
class AddPageTests(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _callFUT(self, context, request):
from tutorial.views import add_page
return add_page(context, request)
def test_it_notsubmitted(self):
context = testing.DummyModel()
request = testing.DummyRequest()
request.subpath = ['AnotherPage']
renderer = testing.registerDummyRenderer('templates/edit.pt')
response = self._callFUT(context, request)
self.assertEqual(renderer.request, request)
self.assertEqual(renderer.page.data, '')
def test_it_submitted(self):
context = testing.DummyModel()
request = testing.DummyRequest({'form.submitted':True,
'body':'Hello yo!'})
request.subpath = ['AnotherPage']
response = self._callFUT(context, request)
page = context['AnotherPage']
self.assertEqual(page.data, 'Hello yo!')
self.assertEqual(page.__name__, 'AnotherPage')
self.assertEqual(page.__parent__, context)
class EditPageTests(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _callFUT(self, context, request):
from tutorial.views import edit_page
return edit_page(context, request)
def test_it_notsubmitted(self):
context = testing.DummyModel()
request = testing.DummyRequest()
renderer = testing.registerDummyRenderer('templates/edit.pt')
response = self._callFUT(context, request)
self.assertEqual(renderer.request, request)
self.assertEqual(renderer.page, context)
def test_it_submitted(self):
context = testing.DummyModel()
request = testing.DummyRequest({'form.submitted':True,
'body':'Hello yo!'})
renderer = testing.registerDummyRenderer('templates/edit.pt')
response = self._callFUT(context, request)
self.assertEqual(response.location, 'http://example.com/')
self.assertEqual(context.data, 'Hello yo!')
|
We can run these tests by using setup.py test in the same way we did in Running the Tests. Assuming our shell’s current working directory is the “tutorial” distribution directory:
On UNIX:
$ ../bin/python setup.py test -q
On Windows:
c:\bigfntut\tutorial> ..\Scripts\python setup.py test -q
The expected result looks something like:
.........
----------------------------------------------------------------------
Ran 9 tests in 0.203s
OK
The configure.zcml file contains view declarations which serve to map URLs (via traversal) to view functions. You’ll need to add five view declarations to configure.zcml.
As a result of our edits, the configure.zcml file should look something like so:
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 | <configure xmlns="http://namespaces.repoze.org/bfg">
<!-- this must be included for the view declarations to work -->
<include package="repoze.bfg.includes" />
<view
for=".models.Wiki"
view=".views.static_view"
name="static"
/>
<view
for=".models.Wiki"
view=".views.view_wiki"
/>
<view
for=".models.Wiki"
name="add_page"
view=".views.add_page"
/>
<view
for=".models.Page"
view=".views.view_page"
/>
<view
for=".models.Page"
name="edit_page"
view=".views.edit_page"
/>
</configure>
|
Let’s take a look at our tutorial.ini file. The contents of the file are as follows:
[DEFAULT]
debug = true
[app:zodb]
use = egg:tutorial#app
reload_templates = true
debug_authorization = false
debug_notfound = false
zodb_uri = file://%(here)s/Data.fs?connection_cache_size=20000
[pipeline:main]
pipeline =
egg:repoze.zodbconn#closer
egg:repoze.tm#tm
zodb
[server:main]
use = egg:Paste#http
host = 0.0.0.0
port = 6543
Within tutorial.ini, note the existence of a [pipeline:main] section which specifies our WSGI pipeline. This “pipeline” will be served up as our WSGI application. As far as the WSGI server is concerned the pipeline is our application. Simpler configurations don’t use a pipeline: instead they expose a single WSGI application as “main”. Our setup is more complicated, so we use a pipeline.
“egg:repoze.zodbconn#closer” is at the “top” of the pipeline. This is a piece of middleware which closes the ZODB connection opened by the PersistentApplicationFinder at the end of the request.
“egg:repoze.tm#tm” is the second piece of middleware in the pipeline. This commits a transaction near the end of the request unless there’s an exception raised.
Let’s add a piece of middleware to the WSGI pipeline. “egg:Paste#evalerror” middleware which displays debuggable errors in the browser while you’re developing (not recommended for deployment). Let’s insert evalerror into the pipeline right below “egg:repoze.zodbconn#closer”, making our resulting tutorial.ini file look like so:
[DEFAULT]
debug = true
[app:zodb]
use = egg:tutorial#app
reload_templates = true
debug_authorization = false
debug_notfound = false
zodb_uri = file://%(here)s/Data.fs?connection_cache_size=20000
[pipeline:main]
pipeline =
egg:repoze.zodbconn#closer
egg:Paste#evalerror
egg:repoze.tm#tm
zodb
[server:main]
use = egg:Paste#http
host = 0.0.0.0
port = 6543
Once we’ve set up the WSGI pipeline properly, we can finally examine our application in a browser. The views we’ll try are as follows: