ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2730

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

37.6. DEFINING VIEWS

19content = wikiwords.sub(check, content)

20edit_url = request.route_url(’edit_page’, pagename=pagename)

21return dict(page=page, content=content, edit_url=edit_url)

The curried check() function 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 already contains a page with the matched WikiWord name, check() 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, check() 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 return a dictionary with a number of arguments. The fact that view_page() returns a dictionary (as opposed to a response object) is a cue to Pyramid that it should try to use a renderer associated with the view configuration to render a template. In our case, the template which will be rendered will be the templates/view.pt template, as indicated in the @view_config decorator that is applied to view_page().

The add_page view function

add_page() is 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. add_page() also acts as a handler for the form that is generated when we want to add a page object. The matchdict attribute of the request passed to the add_page() view will have the values we need to construct URLs and find model objects.

1 @view_config(route_name=’add_page’, renderer=’templates/edit.pt’) 2 def add_page(request):

3name = request.matchdict[’pagename’]

4 if ’form.submitted’ in request.params:

5 body = request.params[’body’]

6page = Page(name, body)

7DBSession.add(page)

8return HTTPFound(location = request.route_url(’view_page’,

9

pagename=name))

10save_url = request.route_url(’add_page’, pagename=name)

11page = Page(’’, ’’)

12return dict(page=page, save_url=save_url)

465


37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

The matchdict will have a ’pagename’ key that matches the name of the page we’d like to add. If our add view is invoked via, e.g. http://localhost:6543/add_page/SomeName, the value for

’pagename’ in the matchdict will be ’SomeName’.

If the view execution is not a result of a form submission (i.e. the expression ’form.submitted’ in request.params is False), the view callable renders a template. To do so, it generates a “save url” which the template uses as the form post URL during rendering. We’re lazy here, so we’re going to use the same template (templates/edit.pt) for the add view as well as the page edit view. To do so we create a dummy Page object in order to satisfy the edit form’s desire to have some page object exposed as page. Pyramid will render the template associated with this view to a response.

If the view execution is a result of a form submission (i.e. the expression ’form.submitted’ in request.params is True), we scrape the page body from the form data, create a Page object with this page body and the name taken from matchdict[’pagename’], and save it into the database using DBSession.add. We then redirect back to the view_page view for the newly created page.

The edit_page view function

edit_page() is 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 matchdict attribute of the request passed to the edit_page view will have a ’pagename’ key matching the name of the page the user wants to edit.

1 @view_config(route_name=’edit_page’, renderer=’templates/edit.pt’) 2 def edit_page(request):

3name = request.matchdict[’pagename’]

4 page = DBSession.query(Page).filter_by(name=name).one() 5 if ’form.submitted’ in request.params:

6page.data = request.params[’body’]

7DBSession.add(page)

8return HTTPFound(location = request.route_url(’view_page’,

9

pagename=name))

10return dict(

11page=page,

12save_url = request.route_url(’edit_page’, pagename=name),

13)

If the view execution is not a result of a form submission (i.e. the expression ’form.submitted’ in request.params is False), the view simply renders the edit form, passing the page object and a save_url which will be used as the action of the generated form.

If the view execution is a result of a form submission (i.e. the expression ’form.submitted’ in request.params is True), the view grabs the body element of the request parameters and sets it as the data attribute of the page object. It then redirects to the view_page view of the wiki page.

466



37.6. DEFINING VIEWS

37.6.4 Adding Templates

The views we’ve added all reference a template. Each template is a Chameleon ZPT template. These templates will live in the templates directory of our tutorial package.

The view.pt Template

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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:tal="http://xml.zope.org/namespaces/tal">

<head>

<title>${page.name} - Pyramid tutorial wiki (based on TurboGears 20-Minute Wiki)</title>

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <meta name="keywords" content="python web application" />

<meta name="description" content="pyramid web application" /> <link rel="shortcut icon"

href="${request.static_url(’tutorial:static/favicon.ico’)}" /> <link rel="stylesheet"

href="${request.static_url(’tutorial:static/pylons.css’)}" type="text/css" media="screen" charset="utf-8" />

<!--[if lte IE 6]> <link rel="stylesheet"

href="${request.static_url(’tutorial:static/ie6.css’)}" type="text/css" media="screen" charset="utf-8" />

<![endif]-->

</head>

<body>

<div id="wrap">

<div id="top-small">

<div class="top-small align-center">

<div>

<img width="220" height="50" alt="pyramid" src="${request.static_url(’tutorial:static/pyramid-small.png’)}" />

</div>

467


37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

</div>

</div>

<div id="middle">

<div class="middle align-right">

<div id="left" class="app-welcome align-left"> Viewing <b><span tal:replace="page.name">Page Name

Goes Here</span></b><br/>

You can return to the

<a href="${request.application_url}">FrontPage</a>.<br/>

</div>

<div id="right" class="app-welcome align-right"></div>

</div>

</div>

<div id="bottom">

<div class="bottom">

<div tal:replace="structure content"> Page text goes here.

</div>

<p>

<a tal:attributes="href edit_url" href=""> Edit this page

</a>

</p>

</div>

</div>

</div>

<div id="footer"> <div class="footer"

>© Copyright 2008-2011, Agendaless Consulting.</div>

</div>

</body>

</html>

latex-note.png

The names available for our use in a template are always those that are present in the dictionary returned by the view callable. But our templates make use of a request object that none of our tutorial views return in their dictionary. This value appears as if “by magic”. However, request is one of several names that are available “by default” in a template when a template renderer is used. See *.pt or *.txt: Chameleon Template Renderers for more information about other names that are available by default in a template when a Chameleon template is used as a renderer.

468