~ubuntuone-pqm-team/python-timeline-django/trunk

« back to all changes in this revision

Viewing changes to timeline_django/middleware.py

  • Committer: James Westby
  • Date: 2012-01-27 18:44:27 UTC
  • mto: (1.2.2 cursor-wrapper)
  • mto: This revision was merged to the branch mainline in revision 3.
  • Revision ID: james.westby@canonical.com-20120127184427-4cvnibadh70w4t8r
Add the middleware that will save the timeline.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import threading
 
2
 
 
3
 
 
4
TIMELINE_VAR = 'timeline'
 
5
 
 
6
 
 
7
_thread_local = threading.local()
 
8
 
 
9
 
 
10
def get_timeline():
 
11
    """Get the timeline associated with the current request, if any.
 
12
 
 
13
    If `TimelineMiddleware` saved a `Timeline` object at the start of
 
14
    the request calling this function will return it. If there isn't
 
15
    a saved timeline then `None` will be returned.
 
16
    """
 
17
    return getattr(_thread_local, TIMELINE_VAR, None)
 
18
 
 
19
 
 
20
class TimelineMiddleware(object):
 
21
    """Save a `Timeline` as a thread local.
 
22
 
 
23
    This middleware looks in `request.environ` for a `timeline.timeline`
 
24
    key, and if it is present it stores it in a thread local variable,
 
25
    so that `get_timeline` will return it when later called in that
 
26
    thread.
 
27
    """
 
28
 
 
29
    TIMELINE_ENVIRON_KEY = 'timeline.timeline'
 
30
 
 
31
    def process_request(self, request):
 
32
        if self.TIMELINE_ENVIRON_KEY in request.environ:
 
33
            setattr(_thread_local, TIMELINE_VAR,
 
34
                    request.environ[self.TIMELINE_ENVIRON_KEY])