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

14. REQUEST AND RESPONSE OBJECTS

14.1.7 Cleaning Up After a Request

Sometimes it’s required that some cleanup be performed at the end of a request when a database connection is involved.

For example, let’s say you have a mypackage Pyramid application package that uses SQLAlchemy, and you’d like the current SQLAlchemy database session to be removed after each request. Put the following in the mypackage.__init__ module:

1 from mypackage.models import DBSession

2

3 from pyramid.events import subscriber

4 from pyramid.events import NewRequest

5

6 def cleanup_callback(request):

7DBSession.remove()

8

9 @subscriber(NewRequest)

10def add_cleanup_callback(event):

11event.request.add_finished_callback(cleanup_callback)

Registering the cleanup_callback finished callback at the start of a request (by causing the add_cleanup_callback to receive a pyramid.events.NewRequest event at the start of each request) will cause the DBSession to be removed whenever request processing has ended. Note that in the example above, for the pyramid.events.subscriber decorator to “work”, the pyramid.config.Configurator.scan() method must be called against your mypackage package during application initialization.

latex-note.png

This is only an example. In particular, it is not necessary to cause DBSession.remove to be called in an application generated from any Pyramid scaffold, because these all use the pyramid_tm package. The cleanup done by DBSession.remove is unnecessary when pyramid_tm middleware is configured into the application.

14.1.8 More Details

More detail about the request object API is available in:

168

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