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

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

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

Добавлен: 02.01.2026

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

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

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

37.6. DEFINING VIEWS

The edit.pt Template

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 following:

<!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>

</div>

</div>

<div id="middle">

<div class="middle align-right">

<div id="left" class="app-welcome align-left">

Editing <b><span tal:replace="page.name">Page Name Goes Here</span></b><br/>

469


37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

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">

<form action="${save_url}" method="post">

<textarea name="body" tal:content="page.data" rows="10" cols="60"/><br/>

<input type="submit" name="form.submitted" value="Save"/>

</form>

</div>

</div>

</div>

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

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

</div>

</body>

</html>

Static Assets

Our templates name a single static asset named pylons.css. We don’t need to create this file within our package’s static directory because it was provided at the time we created the project. This file is a little too long to replicate within the body of this guide, however it is available online.

This

CSS file will be accessed via e.g. http://localhost:6543/static/pylons.css

by

virtue

of the call to add_static_view directive we’ve

made in the __init__.py

file.

 

Any

number and type

of

static

assets

can

be

placed in

this directory (or subdirecto-

ries)

and are just referred to

by

URL

or by

using

the

convenience method static_url e.g.

request.static_url(’{{package}}:static/foo.css’) within templates.

37.6.5 Adding Routes to __init__.py

The __init__.py file contains pyramid.config.Configurator.add_route() calls which serve to add routes to our application. First, we’ll get rid of the existing route created by the template using the name ’home’. It’s only an example and isn’t relevant to our application.

We then need to add four calls to add_route. Note that the ordering of these declarations is very important. route declarations are matched in the order they’re found in the __init__.py file.

470


37.6. DEFINING VIEWS

1.Add a declaration which maps the pattern / (signifying the root URL) to the route named view_wiki. It maps to our view_wiki view callable by virtue of the @view_config attached to the view_wiki view function indicating route_name=’view_wiki’.

2.Add a declaration which maps the pattern /{pagename} to the route named view_page.

This is the regular view for a page. It maps to our view_page view callable by virtue of the @view_config attached to the view_page view function indicating route_name=’view_page’.

3.Add a declaration which maps the pattern /add_page/{pagename} to the route named add_page. This is the add view for a new page. It maps to our add_page view callable by virtue of the @view_config attached to the add_page view function indicating route_name=’add_page’.

4.Add a declaration which maps the pattern /{pagename}/edit_page to the route named edit_page. This is the edit view for a page. It maps to our edit_page view callable by virtue of the @view_config attached to the edit_page view function indicating route_name=’edit_page’.

As a result of our edits, the __init__.py file should look something like:

1

from pyramid.config

import Configurator

2

from

sqlalchemy import engine_from_config

3

 

 

 

4

from

.models import

DBSession

5

6 def main(global_config, **settings):

7""" This function returns a Pyramid WSGI application.

8"""

9engine = engine_from_config(settings, ’sqlalchemy.’)

10DBSession.configure(bind=engine)

11config = Configurator(settings=settings)

12config.add_static_view(’static’, ’static’, cache_max_age=3600)

13config.add_route(’view_wiki’, ’/’)

14config.add_route(’view_page’, ’/{pagename}’)

15config.add_route(’add_page’, ’/add_page/{pagename}’)

16config.add_route(’edit_page’, ’/{pagename}/edit_page’)

17config.scan()

18return config.make_wsgi_app()

(The highlighted lines are the ones that need to be added or edited.)

471



37. SQLALCHEMY + URL DISPATCH WIKI TUTORIAL

37.6.6 Viewing the Application in a Browser

We can finally examine our application in a browser (See Starting the Application). The views we’ll try are as follows:

Visiting http://localhost:6543 in a browser invokes the view_wiki view. This always redirects to the view_page view of the FrontPage page object.

Visiting http://localhost:6543/FrontPage in a browser invokes the view_page view of the front page page object.

Visiting http://localhost:6543/FrontPage/edit_page in a browser invokes the edit view for the front page object.

Visiting http://localhost:6543/add_page/SomePageName in a browser invokes the add view for a page.

Try generating an error within the body of a view by adding code to the top of it that generates an exception (e.g. raise Exception(’Forced Exception’)). Then visit the error-raising view in a browser. You should see an interactive exception handler in the browser which allows you to examine values in a post-mortem mode.

37.7 Adding Authorization

Pyramid provides facilities for authentication and authorization. We’ll make use of both features to provide security to our application. Our application currently allows anyone with access to the server to view, edit, and add pages to our wiki. We’ll change that to allow only people who possess a specific username (editor) to add and edit wiki pages but we’ll continue allowing anyone with access to the server to view pages.

We will do the following steps:

Add a root factory with an ACL (models.py).

Add an authentication policy and an authorization policy (__init__.py).

Add an authentication policy callback (new security.py module).

Add login and logout views (views.py).

Add permission declarations to the edit_page and add_page views (views.py).

Make the existing views return a logged_in flag to the renderer (views.py).

Add a login template (new login.pt).

Add a “Logout” link to be shown when logged in and viewing or editing a page (view.pt, edit.pt).

The source code for this tutorial stage can be browsed at http://github.com/Pylons/pyramid/tree/1.3- branch/docs/tutorials/wiki2/src/authorization/.

472