/usr/lib/python3/dist-packages/cement/ext/ext_memcached.py is in python3-cement 2.10.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | """
The Memcached Extension provides application caching and key/value store
support via Memcache.
Requirements
------------
* pylibmc (``pip install pylibmc``)
* Note: There are known issues installing ``pylibmc`` on OSX/Homebrew
via PIP. This post `might be helpful \
<http://stackoverflow.com/questions/14803310/\
error-when-install-pylibmc-using-pip>`_.
Configuration
-------------
This extension honors the following config settings
under a ``[cache.memcached]`` section in any configuration file:
* **expire_time** - The default time in second to expire items in the
cache. Default: 0 (does not expire).
* **hosts** - List of Memcached servers.
Configurations can be passed as defaults to a CementApp:
.. code-block:: python
from cement.core.foundation import CementApp
from cement.utils.misc import init_defaults
defaults = init_defaults('myapp', 'cache.memcached')
defaults['cache.memcached']['expire_time'] = 0
defaults['cache.memcached']['hosts'] = ['127.0.0.1']
class MyApp(CementApp):
class Meta:
label = 'myapp'
config_defaults = defaults
extensions = ['memcached']
cache_handler = 'memcached'
Additionally, an application configuration file might have a section like
the following:
.. code-block:: text
[myapp]
# set the cache handler to use
cache_handler = memcached
[cache.memcached]
# time in seconds that an item in the cache will expire
expire_time = 3600
# comma seperated list of memcached servers
hosts = 127.0.0.1, cache.example.com
Usage
-----
.. code-block:: python
from cement.core import foundation
from cement.utils.misc import init_defaults
defaults = init_defaults('myapp', 'memcached')
defaults['cache.memcached']['expire_time'] = 300 # seconds
defaults['cache.memcached']['hosts'] = ['127.0.0.1']
class MyApp(foundation.CementApp):
class Meta:
label = 'myapp'
config_defaults = defaults
extensions = ['memcached']
cache_handler = 'memcached'
with MyApp() as app:
# Run the app
app.run()
# Set a cached value
app.cache.set('my_key', 'my value')
# Get a cached value
app.cache.get('my_key')
# Delete a cached value
app.cache.delete('my_key')
# Delete the entire cache
app.cache.purge()
"""
import pylibmc
from ..core import cache
from ..utils.misc import minimal_logger
LOG = minimal_logger(__name__)
class MemcachedCacheHandler(cache.CementCacheHandler):
"""
This class implements the :ref:`ICache <cement.core.cache>`
interface. It provides a caching interface using the
`pylibmc <http://sendapatch.se/projects/pylibmc/>`_ library.
**Note** This extension has an external dependency on ``pylibmc``. You
must include ``pylibmc`` in your applications dependencies as Cement
explicitly does *not* include external dependencies for optional
extensions.
"""
class Meta:
"""Handler meta-data."""
interface = cache.ICache
label = 'memcached'
config_defaults = dict(
hosts=['127.0.0.1'],
expire_time=0,
)
def __init__(self, *args, **kw):
super(MemcachedCacheHandler, self).__init__(*args, **kw)
self.mc = None
def _setup(self, *args, **kw):
super(MemcachedCacheHandler, self)._setup(*args, **kw)
self._fix_hosts()
self.mc = pylibmc.Client(self._config('hosts'))
def _fix_hosts(self):
"""
Useful to fix up the hosts configuration (i.e. convert a
comma-separated string into a list). This function does not return
anything, however it is expected to set the `hosts` value of the
``[cache.memcached]`` section (which is what this extension reads for
it's host configution).
:returns: ``None``
"""
hosts = self._config('hosts')
fixed_hosts = []
if type(hosts) == str:
parts = hosts.split(',')
for part in parts:
fixed_hosts.append(part.strip())
elif type(hosts) == list:
fixed_hosts = hosts
self.app.config.set(self._meta.config_section, 'hosts', fixed_hosts)
def get(self, key, fallback=None, **kw):
"""
Get a value from the cache. Any additional keyword arguments will be
passed directly to `pylibmc` get function.
:param key: The key of the item in the cache to get.
:param fallback: The value to return if the item is not found in the
cache.
:returns: The value of the item in the cache, or the `fallback` value.
"""
LOG.debug("getting cache value using key '%s'" % key)
res = self.mc.get(key, **kw)
if res is None:
return fallback
else:
return res
def _config(self, key):
"""
This is a simple wrapper, and is equivalent to:
``self.app.config.get('cache.memcached', <key>)``.
:param key: The key to get a config value from the 'cache.memcached'
config section.
:returns: The value of the given key.
"""
return self.app.config.get(self._meta.config_section, key)
def set(self, key, value, time=None, **kw):
"""
Set a value in the cache for the given ``key``. Any additional
keyword arguments will be passed directly to the `pylibmc` set
function.
:param key: The key of the item in the cache to set.
:param value: The value of the item to set.
:param time: The expiration time (in seconds) to keep the item cached.
Defaults to `expire_time` as defined in the applications
configuration.
:returns: ``None``
"""
if time is None:
time = int(self._config('expire_time'))
self.mc.set(key, value, time=time, **kw)
def delete(self, key, **kw):
"""
Delete an item from the cache for the given ``key``. Any additional
keyword arguments will be passed directly to the `pylibmc` delete
function.
:param key: The key to delete from the cache.
:returns: ``None``
"""
self.mc.delete(key, **kw)
def purge(self, **kw):
"""
Purge the entire cache, all keys and values will be lost. Any
additional keyword arguments will be passed directly to the
pylibmc ``flush_all()`` function.
:returns: ``None``
"""
self.mc.flush_all(**kw)
def load(app):
app.handler.register(MemcachedCacheHandler)
|