Show More
@@ -1,204 +1,150 b'' | |||||
1 | # Copyright (c) 2010 Agendaless Consulting and Contributors. |
|
1 | # Copyright (c) 2010 Agendaless Consulting and Contributors. | |
2 | # (http://www.agendaless.com), All Rights Reserved |
|
2 | # (http://www.agendaless.com), All Rights Reserved | |
3 | # License: BSD-derived (http://www.repoze.org/LICENSE.txt) |
|
3 | # License: BSD-derived (http://www.repoze.org/LICENSE.txt) | |
4 | # With Patches from RhodeCode GmBH |
|
4 | # With Patches from RhodeCode GmBH | |
5 |
|
5 | |||
6 |
|
6 | |||
7 | import os |
|
7 | import os | |
8 |
|
8 | |||
9 | from beaker import cache |
|
9 | from beaker import cache | |
10 | from beaker.session import SessionObject |
|
10 | from beaker.session import SessionObject | |
11 | from beaker.util import coerce_cache_params |
|
11 | from beaker.util import coerce_cache_params | |
12 | from beaker.util import coerce_session_params |
|
12 | from beaker.util import coerce_session_params | |
13 |
|
13 | |||
14 | from pyramid.interfaces import ISession |
|
14 | from pyramid.interfaces import ISession | |
15 | from pyramid.settings import asbool |
|
15 | from pyramid.settings import asbool | |
16 | from zope.interface import implementer |
|
16 | from zope.interface import implementer | |
17 |
|
17 | |||
18 | from binascii import hexlify |
|
18 | from binascii import hexlify | |
19 |
|
19 | |||
20 |
|
20 | |||
21 | def BeakerSessionFactoryConfig(**options): |
|
21 | def BeakerSessionFactoryConfig(**options): | |
22 | """ Return a Pyramid session factory using Beaker session settings |
|
22 | """ Return a Pyramid session factory using Beaker session settings | |
23 | supplied directly as ``**options``""" |
|
23 | supplied directly as ``**options``""" | |
24 |
|
24 | |||
25 | class PyramidBeakerSessionObject(SessionObject): |
|
25 | class PyramidBeakerSessionObject(SessionObject): | |
26 | _options = options |
|
26 | _options = options | |
27 | _cookie_on_exception = _options.pop('cookie_on_exception', True) |
|
27 | _cookie_on_exception = _options.pop('cookie_on_exception', True) | |
28 | _constant_csrf_token = _options.pop('constant_csrf_token', False) |
|
28 | _constant_csrf_token = _options.pop('constant_csrf_token', False) | |
29 |
|
29 | |||
30 | def __init__(self, request): |
|
30 | def __init__(self, request): | |
31 | SessionObject.__init__(self, request.environ, **self._options) |
|
31 | SessionObject.__init__(self, request.environ, **self._options) | |
32 |
|
32 | |||
33 | def session_callback(request, response): |
|
33 | def session_callback(request, response): | |
34 | exception = getattr(request, 'exception', None) |
|
34 | exception = getattr(request, 'exception', None) | |
35 | file_response = getattr(request, '_file_response', None) |
|
35 | file_response = getattr(request, '_file_response', None) | |
36 |
|
36 | |||
37 | if file_response is None \ |
|
37 | if file_response is None \ | |
38 | and (exception is None or self._cookie_on_exception) \ |
|
38 | and (exception is None or self._cookie_on_exception) \ | |
39 | and self.accessed(): |
|
39 | and self.accessed(): | |
40 | self.persist() |
|
40 | self.persist() | |
41 | headers = self.__dict__['_headers'] |
|
41 | headers = self.__dict__['_headers'] | |
42 | if headers.get('set_cookie') and headers.get('cookie_out'): |
|
42 | if headers.get('set_cookie') and headers.get('cookie_out'): | |
43 | response.headerlist.append(('Set-Cookie', headers['cookie_out'])) |
|
43 | response.headerlist.append(('Set-Cookie', headers['cookie_out'])) | |
44 | request.add_response_callback(session_callback) |
|
44 | request.add_response_callback(session_callback) | |
45 |
|
45 | |||
46 | # ISession API |
|
46 | # ISession API | |
47 |
|
47 | |||
48 | @property |
|
48 | @property | |
49 | def id(self): |
|
49 | def id(self): | |
50 | # this is as inspected in SessionObject.__init__ |
|
50 | # this is as inspected in SessionObject.__init__ | |
51 | if self.__dict__['_params'].get('type') != 'cookie': |
|
51 | if self.__dict__['_params'].get('type') != 'cookie': | |
52 | return self._session().id |
|
52 | return self._session().id | |
53 | return None |
|
53 | return None | |
54 |
|
54 | |||
55 | @property |
|
55 | @property | |
56 | def new(self): |
|
56 | def new(self): | |
57 | return self.last_accessed is None |
|
57 | return self.last_accessed is None | |
58 |
|
58 | |||
59 | changed = SessionObject.save |
|
59 | changed = SessionObject.save | |
60 |
|
60 | |||
61 | # modifying dictionary methods |
|
61 | # modifying dictionary methods | |
62 |
|
62 | |||
63 | @call_save |
|
63 | @call_save | |
64 | def clear(self): |
|
64 | def clear(self): | |
65 | return self._session().clear() |
|
65 | return self._session().clear() | |
66 |
|
66 | |||
67 | @call_save |
|
67 | @call_save | |
68 | def update(self, d, **kw): |
|
68 | def update(self, d, **kw): | |
69 | return self._session().update(d, **kw) |
|
69 | return self._session().update(d, **kw) | |
70 |
|
70 | |||
71 | @call_save |
|
71 | @call_save | |
72 | def setdefault(self, k, d=None): |
|
72 | def setdefault(self, k, d=None): | |
73 | return self._session().setdefault(k, d) |
|
73 | return self._session().setdefault(k, d) | |
74 |
|
74 | |||
75 | @call_save |
|
75 | @call_save | |
76 | def pop(self, k, d=None): |
|
76 | def pop(self, k, d=None): | |
77 | return self._session().pop(k, d) |
|
77 | return self._session().pop(k, d) | |
78 |
|
78 | |||
79 | @call_save |
|
79 | @call_save | |
80 | def popitem(self): |
|
80 | def popitem(self): | |
81 | return self._session().popitem() |
|
81 | return self._session().popitem() | |
82 |
|
82 | |||
83 | __setitem__ = call_save(SessionObject.__setitem__) |
|
83 | __setitem__ = call_save(SessionObject.__setitem__) | |
84 | __delitem__ = call_save(SessionObject.__delitem__) |
|
84 | __delitem__ = call_save(SessionObject.__delitem__) | |
85 |
|
85 | |||
86 | # Flash API methods |
|
86 | # Flash API methods | |
87 | def flash(self, msg, queue='', allow_duplicate=True): |
|
87 | def flash(self, msg, queue='', allow_duplicate=True): | |
88 | storage = self.setdefault('_f_' + queue, []) |
|
88 | storage = self.setdefault('_f_' + queue, []) | |
89 | if allow_duplicate or (msg not in storage): |
|
89 | if allow_duplicate or (msg not in storage): | |
90 | storage.append(msg) |
|
90 | storage.append(msg) | |
91 |
|
91 | |||
92 | def pop_flash(self, queue=''): |
|
92 | def pop_flash(self, queue=''): | |
93 | storage = self.pop('_f_' + queue, []) |
|
93 | storage = self.pop('_f_' + queue, []) | |
94 | return storage |
|
94 | return storage | |
95 |
|
95 | |||
96 | def peek_flash(self, queue=''): |
|
96 | def peek_flash(self, queue=''): | |
97 | storage = self.get('_f_' + queue, []) |
|
97 | storage = self.get('_f_' + queue, []) | |
98 | return storage |
|
98 | return storage | |
99 |
|
99 | |||
100 | # CSRF API methods |
|
100 | # CSRF API methods | |
101 | def new_csrf_token(self): |
|
101 | def new_csrf_token(self): | |
102 | token = (self._constant_csrf_token |
|
102 | token = (self._constant_csrf_token | |
103 | or hexlify(os.urandom(20)).decode('ascii')) |
|
103 | or hexlify(os.urandom(20)).decode('ascii')) | |
104 | self['_csrft_'] = token |
|
104 | self['_csrft_'] = token | |
105 | return token |
|
105 | return token | |
106 |
|
106 | |||
107 | def get_csrf_token(self): |
|
107 | def get_csrf_token(self): | |
108 | token = self.get('_csrft_', None) |
|
108 | token = self.get('_csrft_', None) | |
109 | if token is None: |
|
109 | if token is None: | |
110 | token = self.new_csrf_token() |
|
110 | token = self.new_csrf_token() | |
111 | return token |
|
111 | return token | |
112 |
|
112 | |||
113 | return implementer(ISession)(PyramidBeakerSessionObject) |
|
113 | return implementer(ISession)(PyramidBeakerSessionObject) | |
114 |
|
114 | |||
115 |
|
115 | |||
116 | def call_save(wrapped): |
|
116 | def call_save(wrapped): | |
117 | """ By default, in non-auto-mode beaker badly wants people to |
|
117 | """ By default, in non-auto-mode beaker badly wants people to | |
118 | call save even though it should know something has changed when |
|
118 | call save even though it should know something has changed when | |
119 | a mutating method is called. This hack should be removed if |
|
119 | a mutating method is called. This hack should be removed if | |
120 | Beaker ever starts to do this by default. """ |
|
120 | Beaker ever starts to do this by default. """ | |
121 | def save(session, *arg, **kw): |
|
121 | def save(session, *arg, **kw): | |
122 | value = wrapped(session, *arg, **kw) |
|
122 | value = wrapped(session, *arg, **kw) | |
123 | session.save() |
|
123 | session.save() | |
124 | return value |
|
124 | return value | |
125 | save.__doc__ = wrapped.__doc__ |
|
125 | save.__doc__ = wrapped.__doc__ | |
126 | return save |
|
126 | return save | |
127 |
|
127 | |||
128 |
|
128 | |||
129 | def session_factory_from_settings(settings): |
|
129 | def session_factory_from_settings(settings): | |
130 | """ Return a Pyramid session factory using Beaker session settings |
|
130 | """ Return a Pyramid session factory using Beaker session settings | |
131 | supplied from a Paste configuration file""" |
|
131 | supplied from a Paste configuration file""" | |
132 | prefixes = ('session.', 'beaker.session.') |
|
132 | prefixes = ('session.', 'beaker.session.') | |
133 | options = {} |
|
133 | options = {} | |
134 |
|
134 | |||
135 | # Pull out any config args meant for beaker session. if there are any |
|
135 | # Pull out any config args meant for beaker session. if there are any | |
136 | for k, v in settings.items(): |
|
136 | for k, v in settings.items(): | |
137 | for prefix in prefixes: |
|
137 | for prefix in prefixes: | |
138 | if k.startswith(prefix): |
|
138 | if k.startswith(prefix): | |
139 | option_name = k[len(prefix):] |
|
139 | option_name = k[len(prefix):] | |
140 | if option_name == 'cookie_on_exception': |
|
140 | if option_name == 'cookie_on_exception': | |
141 | v = asbool(v) |
|
141 | v = asbool(v) | |
142 | options[option_name] = v |
|
142 | options[option_name] = v | |
143 |
|
143 | |||
144 | options = coerce_session_params(options) |
|
144 | options = coerce_session_params(options) | |
145 | return BeakerSessionFactoryConfig(**options) |
|
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 | def includeme(config): |
|
148 | def includeme(config): | |
202 | session_factory = session_factory_from_settings(config.registry.settings) |
|
149 | session_factory = session_factory_from_settings(config.registry.settings) | |
203 | config.set_session_factory(session_factory) |
|
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