source: qesdi/wms_ddc_vis/trunk/lib/wms_ddc_vis/lib/modified_beaker_cache_decorator.py @ 5773

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/qesdi/wms_ddc_vis/trunk/lib/wms_ddc_vis/lib/modified_beaker_cache_decorator.py@5773
Revision 5773, 3.6 KB checked in by pnorton, 10 years ago (diff)

Modified the beaker cache decorator that comes with pylons so that it includes response content written to response.write(). Added this decorator to a number of controllers to try and improve the performacne.

Line 
1'''
2Created on 28 Sep 2009
3
4@author: pnorton
5'''
6from pylons.decorators.cache import _make_key, _make_dict_from_args
7
8import inspect
9import logging
10
11from decorator import decorator
12from paste.deploy.converters import asbool
13
14import pylons
15
16log = logging.getLogger(__name__)
17
18def beaker_cache(key="cache_default", expire="never", type="dbm",
19    query_args=False, **b_kwargs):
20    """Cache decorator utilizing Beaker. Caches action or other function that
21    returns a pickle-able object as a result.
22
23    Optional arguments:
24
25    key
26        None - No variable key, uses function name as key
27        "cache_default" - Uses all function arguments as the key
28        string - Use kwargs[key] as key
29        list - Joins the arguments in the list
30    expire
31        Time in seconds before cache expires, defaults to never
32    type
33        Type of cache to use: dbm, memory, file, memcached
34    query_args
35        Uses the query arguments as the key, defaults to False
36
37    If cache_enabled is set to False in the .ini file, then cache is disabled
38    globally.
39    """
40    def wrapper(func, *args, **kwargs):
41        """Decorator wrapper"""
42#        log.debug("Wrapped with key: %s, expire: %s, type: %s, query_args: %s",
43#                  key, expire, type, query_args)
44        enabled = pylons.config.get("cache_enabled", "True")
45        if not asbool(enabled):
46            log.debug("Caching disabled, skipping cache lookup")
47            return func(*args, **kwargs)
48       
49       
50        commonArgs = {'LAYERS': u'coastline', 'STYLES': u'', 'WIDTH': u'320', 'SERVICE': u'WMS', 'FORMAT': u'image/png', 'CRS': u'CRS:84', 'REQUEST': u'GetMap', 'HEIGHT': u'320', 'SRS': u'EPSG:4326', 'VERSION': u'1.3.0', 'EXCEPTIONS': u'application/vnd.ogc.se_inimage', 'TRANSPARENT': u'true'}
51        commonMatch = True
52        params = dict(pylons.request.GET)
53        for k1,v1 in commonArgs.items():
54            if k1 not in params or params[k1] != v1:
55                commonMatch = False
56           
57        my_cache = pylons.cache.get_cache('%s.%s' % (func.__module__, func.__name__), type=type)
58        cache_key = _make_key(func, key, args, kwargs, query_args)
59        if commonMatch:
60            pass
61        else:
62            log.debug("Cache request with key: %s" % (cache_key,))
63       
64        if expire == "never":
65            cache_expire = None
66        else:
67            cache_expire = expire
68       
69       
70        def create_func():
71            if commonMatch:
72                log.debug("Generating Data: BBOX = %s" % (params['BBOX'],))
73            else:
74                log.debug("Generating Data")
75            #log.debug("Creating new cache copy with key: %s, type: %s",
76            #          cache_key, type)
77            result = func(*args, **kwargs)
78            glob_response = pylons.response._current_obj()
79            full_response = dict(headers=glob_response.headers,
80                                 status=glob_response.status_code,
81                                 cookies=glob_response.cookies,
82                                 r_content=glob_response.content,
83                                 content=result)
84            return full_response
85       
86        response = my_cache.get_value(cache_key, createfunc=create_func, 
87                                      expiretime=cache_expire, **b_kwargs)
88       
89        glob_response = pylons.response._current_obj()
90        glob_response.headers = response['headers']
91        glob_response.status_code = response['status']
92        #glob_response.cookies = response['cookies']
93        glob_response.content = response['r_content']
94        return response['content']
95    return decorator(wrapper)
Note: See TracBrowser for help on using the repository browser.