##// END OF EJS Templates
beaker-cache: remove no longer used beaker cache init
milka -
r4601:070c235b stable
parent child Browse files
Show More
@@ -1,204 +1,150 b''
1 1 # Copyright (c) 2010 Agendaless Consulting and Contributors.
2 2 # (http://www.agendaless.com), All Rights Reserved
3 3 # License: BSD-derived (http://www.repoze.org/LICENSE.txt)
4 4 # With Patches from RhodeCode GmBH
5 5
6 6
7 7 import os
8 8
9 9 from beaker import cache
10 10 from beaker.session import SessionObject
11 11 from beaker.util import coerce_cache_params
12 12 from beaker.util import coerce_session_params
13 13
14 14 from pyramid.interfaces import ISession
15 15 from pyramid.settings import asbool
16 16 from zope.interface import implementer
17 17
18 18 from binascii import hexlify
19 19
20 20
21 21 def BeakerSessionFactoryConfig(**options):
22 22 """ Return a Pyramid session factory using Beaker session settings
23 23 supplied directly as ``**options``"""
24 24
25 25 class PyramidBeakerSessionObject(SessionObject):
26 26 _options = options
27 27 _cookie_on_exception = _options.pop('cookie_on_exception', True)
28 28 _constant_csrf_token = _options.pop('constant_csrf_token', False)
29 29
30 30 def __init__(self, request):
31 31 SessionObject.__init__(self, request.environ, **self._options)
32 32
33 33 def session_callback(request, response):
34 34 exception = getattr(request, 'exception', None)
35 35 file_response = getattr(request, '_file_response', None)
36 36
37 37 if file_response is None \
38 38 and (exception is None or self._cookie_on_exception) \
39 39 and self.accessed():
40 40 self.persist()
41 41 headers = self.__dict__['_headers']
42 42 if headers.get('set_cookie') and headers.get('cookie_out'):
43 43 response.headerlist.append(('Set-Cookie', headers['cookie_out']))
44 44 request.add_response_callback(session_callback)
45 45
46 46 # ISession API
47 47
48 48 @property
49 49 def id(self):
50 50 # this is as inspected in SessionObject.__init__
51 51 if self.__dict__['_params'].get('type') != 'cookie':
52 52 return self._session().id
53 53 return None
54 54
55 55 @property
56 56 def new(self):
57 57 return self.last_accessed is None
58 58
59 59 changed = SessionObject.save
60 60
61 61 # modifying dictionary methods
62 62
63 63 @call_save
64 64 def clear(self):
65 65 return self._session().clear()
66 66
67 67 @call_save
68 68 def update(self, d, **kw):
69 69 return self._session().update(d, **kw)
70 70
71 71 @call_save
72 72 def setdefault(self, k, d=None):
73 73 return self._session().setdefault(k, d)
74 74
75 75 @call_save
76 76 def pop(self, k, d=None):
77 77 return self._session().pop(k, d)
78 78
79 79 @call_save
80 80 def popitem(self):
81 81 return self._session().popitem()
82 82
83 83 __setitem__ = call_save(SessionObject.__setitem__)
84 84 __delitem__ = call_save(SessionObject.__delitem__)
85 85
86 86 # Flash API methods
87 87 def flash(self, msg, queue='', allow_duplicate=True):
88 88 storage = self.setdefault('_f_' + queue, [])
89 89 if allow_duplicate or (msg not in storage):
90 90 storage.append(msg)
91 91
92 92 def pop_flash(self, queue=''):
93 93 storage = self.pop('_f_' + queue, [])
94 94 return storage
95 95
96 96 def peek_flash(self, queue=''):
97 97 storage = self.get('_f_' + queue, [])
98 98 return storage
99 99
100 100 # CSRF API methods
101 101 def new_csrf_token(self):
102 102 token = (self._constant_csrf_token
103 103 or hexlify(os.urandom(20)).decode('ascii'))
104 104 self['_csrft_'] = token
105 105 return token
106 106
107 107 def get_csrf_token(self):
108 108 token = self.get('_csrft_', None)
109 109 if token is None:
110 110 token = self.new_csrf_token()
111 111 return token
112 112
113 113 return implementer(ISession)(PyramidBeakerSessionObject)
114 114
115 115
116 116 def call_save(wrapped):
117 117 """ By default, in non-auto-mode beaker badly wants people to
118 118 call save even though it should know something has changed when
119 119 a mutating method is called. This hack should be removed if
120 120 Beaker ever starts to do this by default. """
121 121 def save(session, *arg, **kw):
122 122 value = wrapped(session, *arg, **kw)
123 123 session.save()
124 124 return value
125 125 save.__doc__ = wrapped.__doc__
126 126 return save
127 127
128 128
129 129 def session_factory_from_settings(settings):
130 130 """ Return a Pyramid session factory using Beaker session settings
131 131 supplied from a Paste configuration file"""
132 132 prefixes = ('session.', 'beaker.session.')
133 133 options = {}
134 134
135 135 # Pull out any config args meant for beaker session. if there are any
136 136 for k, v in settings.items():
137 137 for prefix in prefixes:
138 138 if k.startswith(prefix):
139 139 option_name = k[len(prefix):]
140 140 if option_name == 'cookie_on_exception':
141 141 v = asbool(v)
142 142 options[option_name] = v
143 143
144 144 options = coerce_session_params(options)
145 145 return BeakerSessionFactoryConfig(**options)
146 146
147 147
148 def set_cache_regions_from_settings(settings):
149 """ Add cache support to the Pylons application.
150
151 The ``settings`` passed to the configurator are used to setup
152 the cache options. Cache options in the settings should start
153 with either 'beaker.cache.' or 'cache.'.
154
155 """
156 cache_settings = {'regions': []}
157 for key in settings.keys():
158 for prefix in ['beaker.cache.', 'cache.']:
159 if key.startswith(prefix):
160 name = key.split(prefix)[1].strip()
161 cache_settings[name] = settings[key].strip()
162
163 if ('expire' in cache_settings
164 and isinstance(cache_settings['expire'], basestring)
165 and cache_settings['expire'].lower() in ['none', 'no']):
166 cache_settings['expire'] = None
167
168 coerce_cache_params(cache_settings)
169
170 if 'enabled' not in cache_settings:
171 cache_settings['enabled'] = True
172
173 regions = cache_settings['regions']
174 if regions:
175 for region in regions:
176 if not region:
177 continue
178
179 region_settings = {
180 'data_dir': cache_settings.get('data_dir'),
181 'lock_dir': cache_settings.get('lock_dir'),
182 'expire': cache_settings.get('expire', 60),
183 'enabled': cache_settings['enabled'],
184 'key_length': cache_settings.get('key_length', 250),
185 'type': cache_settings.get('type'),
186 'url': cache_settings.get('url'),
187 }
188 region_prefix = '%s.' % region
189 region_len = len(region_prefix)
190 for key in list(cache_settings.keys()):
191 if key.startswith(region_prefix):
192 region_settings[key[region_len:]] = cache_settings.pop(key)
193
194 if (isinstance(region_settings['expire'], basestring)
195 and region_settings['expire'].lower() in ['none', 'no']):
196 region_settings['expire'] = None
197 coerce_cache_params(region_settings)
198 cache.cache_regions[region] = region_settings
199
200
201 148 def includeme(config):
202 149 session_factory = session_factory_from_settings(config.registry.settings)
203 150 config.set_session_factory(session_factory)
204 set_cache_regions_from_settings(config.registry.settings)
General Comments 0
You need to be logged in to leave comments. Login now