Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/pyramid/threadlocal.py : 72%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import threading
3from pyramid.registry import global_registry
6class ThreadLocalManager(threading.local):
7 def __init__(self, default=None):
8 # http://code.google.com/p/google-app-engine-django/issues/detail?id=119
9 # we *must* use a keyword argument for ``default`` here instead
10 # of a positional argument to work around a bug in the
11 # implementation of _threading_local.local in Python, which is
12 # used by GAE instead of _thread.local
13 self.stack = []
14 self.default = default
16 def push(self, info):
17 self.stack.append(info)
19 set = push # b/c
21 def pop(self):
22 if self.stack:
23 return self.stack.pop()
25 def get(self):
26 try:
27 return self.stack[-1]
28 except IndexError:
29 return self.default()
31 def clear(self):
32 self.stack[:] = []
35def defaults():
36 return {'request': None, 'registry': global_registry}
39manager = ThreadLocalManager(default=defaults)
42def get_current_request():
43 """
44 Return the currently active request or ``None`` if no request
45 is currently active.
47 This function should be used *extremely sparingly*, usually only
48 in unit testing code. It's almost always usually a mistake to use
49 ``get_current_request`` outside a testing context because its
50 usage makes it possible to write code that can be neither easily
51 tested nor scripted.
53 """
54 return manager.get()['request']
57def get_current_registry(
58 context=None
59): # context required by getSiteManager API
60 """
61 Return the currently active :term:`application registry` or the
62 global application registry if no request is currently active.
64 This function should be used *extremely sparingly*, usually only
65 in unit testing code. It's almost always usually a mistake to use
66 ``get_current_registry`` outside a testing context because its
67 usage makes it possible to write code that can be neither easily
68 tested nor scripted.
70 """
71 return manager.get()['registry']
74class RequestContext(object):
75 def __init__(self, request):
76 self.request = request
78 def begin(self):
79 request = self.request
80 registry = request.registry
81 manager.push({'registry': registry, 'request': request})
82 return request
84 def end(self):
85 manager.pop()
87 def __enter__(self):
88 return self.begin()
90 def __exit__(self, *args):
91 self.end()