Hide keyboard shortcuts

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 

2 

3from pyramid.registry import global_registry 

4 

5 

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 

15 

16 def push(self, info): 

17 self.stack.append(info) 

18 

19 set = push # b/c 

20 

21 def pop(self): 

22 if self.stack: 

23 return self.stack.pop() 

24 

25 def get(self): 

26 try: 

27 return self.stack[-1] 

28 except IndexError: 

29 return self.default() 

30 

31 def clear(self): 

32 self.stack[:] = [] 

33 

34 

35def defaults(): 

36 return {'request': None, 'registry': global_registry} 

37 

38 

39manager = ThreadLocalManager(default=defaults) 

40 

41 

42def get_current_request(): 

43 """ 

44 Return the currently active request or ``None`` if no request 

45 is currently active. 

46 

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. 

52 

53 """ 

54 return manager.get()['request'] 

55 

56 

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. 

63 

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. 

69 

70 """ 

71 return manager.get()['registry'] 

72 

73 

74class RequestContext(object): 

75 def __init__(self, request): 

76 self.request = request 

77 

78 def begin(self): 

79 request = self.request 

80 registry = request.registry 

81 manager.push({'registry': registry, 'request': request}) 

82 return request 

83 

84 def end(self): 

85 manager.pop() 

86 

87 def __enter__(self): 

88 return self.begin() 

89 

90 def __exit__(self, *args): 

91 self.end()