Skip to content

Instantly share code, notes, and snippets.

@creiht
Created November 13, 2013 21:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creiht/7457109 to your computer and use it in GitHub Desktop.
Save creiht/7457109 to your computer and use it in GitHub Desktop.
Simple local cache implementation
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)""")
# Since this is in shared memory turn journal off
self.db.execute("pragma journal_mode = OFF")
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