Created
July 19, 2013 17:06
-
-
Save creiht/6040757 to your computer and use it in GitHub Desktop.
First stab at a sqlite based memcache api compatible localcache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sqlite3 | |
import simplejson | |
import time | |
class LocalCache(object): | |
def __init__(self, path='/run/shm/cache.db'): | |
self.db = sqlite3.Connection(path) | |
with self.db: | |
self.db.execute( | |
"""create table if not exists cache ( | |
key TEXT PRIMARY KEY, | |
value TEXT, | |
expires REAL)""") | |
def _sanitize_time(self, time): | |
if time > 0: | |
return time.time() + time | |
def set(self, key, value, serialize=True, time=0, min_compress_len=0): | |
time = self._sanitize_time(time) | |
value = simplejson.dumps(value) | |
with self.db: | |
self.db.execute( | |
"replace into cache (key, value, expires) values (?, ?, ?)", | |
(key, value, time)) | |
def get(self, key): | |
with self.db: | |
result = self.db.execute( | |
"select value, expires from cache where key = ?", | |
(key,)).fetchone() | |
if result and result[1] < time.time(): | |
return simplejson.loads(result[0]) | |
else: | |
return None | |
def incr(self, key, delta=1, time=0): | |
# TODO: there is a race condition here, but this is the | |
# closest I can get at the moment | |
time = self._sanitize_time(time) | |
with self.db: | |
self.db.execute( | |
"insert or ignore into cache (key, value, expires) values (?, ?, ?)", | |
(key, '0', time)) | |
self.db.execute( | |
"update cache set value=value + ? where key = ?", | |
(delta, key)) | |
return self.get(key) | |
def decr(self, key, delta=1, time=0): | |
return self.incr(key, -delta, time) | |
def delete(self, key): | |
with self.db: | |
self.db.execute( | |
"delete from cache where key = ?", | |
key) | |
def set_multi(self, mapping, server_key=None, serialize=True, time=0, | |
min_compress_len=0): | |
raise NotImplementedError() | |
def get_multi(self, keys, server_key=None): | |
raise NotImplementedError() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment