src/pyams_cache/handler/memcached.py
changeset 0 30591ce88556
child 1 e89686e172cd
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_cache/handler/memcached.py	Thu May 18 13:45:02 2017 +0200
@@ -0,0 +1,72 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+import logging
+logger = logging.getLogger('PyAMS (cache)')
+
+# import interfaces
+from pyams_cache.interfaces import ICacheHandler, IAioCacheHandler
+
+# import packages
+from pyams_utils.registry import utility_config
+
+
+# Default Memcached handler
+try:
+    import pylibmc
+except ImportError:
+    logger.debug("Missing pylibmc package. Can't init Memcached cache handler")
+else:
+    @utility_config(name='memcached', provides=ICacheHandler)
+    class MemcachedCacheHandler(object):
+        """Memcached cache handler utility"""
+
+        client = None
+
+        def open(self, server):
+            self.client = pylibmc.Client([server])
+
+        def get(self, key, default=None):
+            result = self.client.get(key)
+            if result is None:
+                result = default
+            return result
+
+        def set(self, key, value):
+            self.client.set(key, value)
+
+
+# Aio Memcached handler
+try:
+    from aiomcache import Client as MemcachedClient
+except ImportError:
+    logger.debug("Missing aiomache package. Can't init Memcached asyncio cache handler.")
+else:
+    @utility_config(name='memcached', provides=IAioCacheHandler)
+    class MemcachedAioCacheHandler(object):
+        """Memcached asyncio cache handler utility"""
+
+        client = None
+
+        def open(self, server):
+            ip, port = server.split(':')
+            self.client = MemcachedClient(ip, int(port))
+
+        def get(self, key, default=None):
+            yield from self.client.get(key, default)
+
+        def set(self, key, value):
+            yield from self.client.set(key, value)