Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

1. PYRAMID INTRODUCTION

1.1.23 Flexible authentication and authorization

Pyramid includes a flexible, pluggable authentication and authorization system. No matter where your user data is stored, or what scheme you’d like to use to permit your users to access your data, you can use a predefined Pyramid plugpoint to plug in your custom authentication and authorization code. If you want to change these schemes later, you can just change it in one place rather than everywhere in your code. It also ships with prebuilt well-tested authentication and authorization schemes out of the box. But what if you don’t want to use Pyramid’s built-in system? You don’t have to. You can just write your own bespoke security code as you would in any other system.

Example: Enabling an Authorization Policy.

1.1.24 Traversal

Traversal is a concept stolen from Zope. It allows you to create a tree of resources, each of which can be addressed by one or more URLs. Each of those resources can have one or more views associated with it. If your data isn’t naturally treelike (or you’re unwilling to create a treelike representation of your data), you aren’t going to find traversal very useful. However, traversal is absolutely fantastic for sites that need to be arbitrarily extensible: it’s a lot easier to add a node to a tree than it is to shoehorn a route into an ordered list of other routes, or to create another entire instance of an application to service a department and glue code to allow disparate apps to share data. It’s a great fit for sites that naturally lend themselves to changing departmental hierarchies, such as content management systems and document management systems. Traversal also lends itself well to systems that require very granular security (“Bob can edit this document” as opposed to “Bob can edit documents”).

Example: hello_traversal_chapter and Much Ado About Traversal.

1.1.25 Tweens

Pyramid has a sort of internal WSGI-middleware-ish pipeline that can be hooked by arbitrary add-ons named “tweens”. The debug toolbar is a “tween”, and the pyramid_tm transaction manager is also. Tweens are more useful than WSGI middleware in some circumstances because they run in the context of Pyramid itself, meaning you have access to templates and other renderers, a “real” request object, and other niceties.

Example: Registering “Tweens”.

14

1.1. WHAT MAKES PYRAMID UNIQUE

1.1.26 View response adapters

A lot is made of the aesthetics of what kinds of objects you’re allowed to return from view callables in various frameworks. In a previous section in this document we showed you that, if you use a renderer, you can usually return a dictionary from a view callable instead of a full-on Response object. But some frameworks allow you to return strings or tuples from view callables. When frameworks allow for this, code looks slightly prettier, because fewer imports need to be done, and there is less code. For example, compare this:

1

2

def aview(request): return "Hello world!"

To this:

1

2

3

4

from pyramid.response import Response

def aview(request):

return Response("Hello world!")

The former is “prettier”, right?

Out of the box, if you define the former view callable (the one that simply returns a string) in Pyramid, when it is executed, Pyramid will raise an exception. This is because “explicit is better than implicit”, in most cases, and by default, Pyramid wants you to return a Response object from a view callable. This is because there’s usually a heck of a lot more to a response object than just its body. But if you’re the kind of person who values such aesthetics, we have an easy way to allow for this sort of thing:

1 from pyramid.config import Configurator

2 from pyramid.response import Response

3

4 def string_response_adapter(s):

5response = Response(s)

6 response.content_type = ’text/html’

7return response

8

9 if __name__ == ’__main__’:

10config = Configurator()

11config.add_response_adapter(string_response_adapter, basestring)

Do that once in your Pyramid application at startup. Now you can return strings from any of your view callables, e.g.:

15

1. PYRAMID INTRODUCTION

1 def helloview(request):

2return "Hello world!"

3

4 def goodbyeview(request):

5return "Goodbye world!"

Oh noes! What if you want to indicate a custom content type? And a custom status code? No fear:

1

from pyramid.config import Configurator

2

 

3

def tuple_response_adapter(val):

4

status_int, content_type, body = val

5response = Response(body)

6 response.content_type = content_type 7 response.status_int = status_int

8return response

9

10def string_response_adapter(body):

11response = Response(body)

12response.content_type = ’text/html’

13response.status_int = 200

14return response

15

16if __name__ == ’__main__’:

17config = Configurator()

18config.add_response_adapter(string_response_adapter, basestring)

19config.add_response_adapter(tuple_response_adapter, tuple)

Once this is done, both of these view callables will work:

1 def aview(request):

2return "Hello world!"

3

4 def anotherview(request):

5return (403, ’text/plain’, "Forbidden")

Pyramid defaults to explicit behavior, because it’s the most generally useful, but provides hooks that allow you to adapt the framework to localized aesthetic desires.

See also Changing How Pyramid Treats View Responses.

16

1.1. WHAT MAKES PYRAMID UNIQUE

1.1.27 “Global” response object

“Constructing these response objects in my view callables is such a chore! And I’m way too lazy to register a response adapter, as per the prior section,” you say. Fine. Be that way:

1 def aview(request):

2response = request.response

3response.body = ’Hello world!’

4 response.content_type = ’text/plain’

5return response

See also Varying Attributes of Rendered Responses.

1.1.28 Automating repetitive configuration

Does Pyramid’s configurator allow you to do something, but you’re a little adventurous and just want it a little less verbose? Or you’d like to offer up some handy configuration feature to other Pyramid users without requiring that we change Pyramid? You can extend Pyramid’s Configurator with your own directives. For example, let’s say you find yourself calling pyramid.config.Configurator.add_view() repetitively. Usually you can take the boring away by using existing shortcuts, but let’s say that this is a case such a way that no existing shortcut works to take the boring away:

1

from pyramid.config import Configurator

2

 

3

config = Configurator()

4

config.add_route(’xhr_route’, ’/xhr/{id}’)

5

config.add_view(’my.package.GET_view’, route_name=’xhr_route’,

6

xhr=True, permission=’view’, request_method=’GET’)

7

config.add_view(’my.package.POST_view’, route_name=’xhr_route’,

8

xhr=True, permission=’view’, request_method=’POST’)

9

config.add_view(’my.package.HEAD_view’, route_name=’xhr_route’,

10

xhr=True, permission=’view’, request_method=’HEAD’)

 

 

Pretty tedious right? You can add a directive to the Pyramid configurator to automate some of the tedium away:

1

2

3

4

5

from pyramid.config import Configurator

def add_protected_xhr_views(config, module): module = config.maybe_dotted(module)

for method in (’GET’, ’POST’, ’HEAD’):

17

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]