Advertisement
Guest User

Untitled

a guest
Aug 31st, 2015
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. import sqlite3
  2. import logging
  3. import os.path
  4. from time import strftime
  5.  
  6. class SqliteCache:
  7. def __init__(self, database_name='cache.sqlite3', logger=None):
  8. self._logger = logger or logging.getLogger(__name__)
  9. self._database_name = database_name
  10. self._ensure_db_exists()
  11.  
  12. def _ensure_db_exists(self):
  13. if not os.path.exists(self._database_name):
  14. with Cursor(self._database_name) as cursor:
  15. cursor.execute('''CREATE TABLE cache (key TEXT PRIMARY KEY, value TEXT, date TEXT)''')
  16.  
  17. def exists(self, key):
  18. with Cursor(self._database_name) as cursor:
  19. cursor.execute("""SELECT key FROM cache WHERE key=?""", (key,))
  20. return cursor.fetchone() is not None
  21.  
  22. def get(self, key):
  23. self._logger.debug("Fetching value '{0}' from cache".format(key))
  24. with Cursor(self._database_name) as cursor:
  25. cursor.execute("""SELECT value FROM cache WHERE key=?""", (key,))
  26. c = cursor.fetchone()
  27. return None if not c else c[0]
  28.  
  29. def cache(self, key, value):
  30. if self.exists(key):
  31. self._logger.debug("The key '{0}' already exists in the cache".format(key))
  32. return
  33.  
  34. self._logger.debug("Caching value with key {0}".format(key))
  35. with Cursor(self._database_name) as cursor:
  36. date = strftime("%Y-%m-%d %H:%M:%S")
  37. cursor.execute('''INSERT INTO cache VALUES (?, ?, ?)''', (key, value, date))
  38.  
  39. class Cursor:
  40. def __init__(self, database_name):
  41. self._database_name = database_name
  42.  
  43. def __enter__(self):
  44. self.conn = sqlite3.connect(self._database_name)
  45. cursor = self.conn.cursor()
  46. return cursor
  47.  
  48. def __exit__(self, type, value, traceback):
  49. self.conn.commit()
  50. self.conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement