Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

57 linhas
1.4 KiB

  1. """
  2. Simple Caching:
  3. Stores key-value pairs in database and enables simple caching
  4. get_item(key).get() returns the cached value if not expired (else returns null)
  5. get_item(key).set(interval = 60000) sets a value to cache, expiring after x seconds
  6. get_item(key).clear() clears an old value
  7. setup() sets up cache
  8. """
  9. import webnotes
  10. class CacheItem:
  11. def __init__(self, key):
  12. """create a new cache"""
  13. self.key = key
  14. def get(self):
  15. """get value"""
  16. try:
  17. return webnotes.conn.sql("select `value` from __CacheItem where `key`=%s and expires_on > NOW()", self.key)[0][0]
  18. except Exception:
  19. return None
  20. def set(self, value, interval=6000):
  21. """set a new value, with interval"""
  22. try:
  23. self.clear()
  24. webnotes.conn.sql("""INSERT INTO
  25. __CacheItem (`key`, `value`, expires_on)
  26. VALUES
  27. (%s, %s, addtime(now(), sec_to_time(%s)))
  28. """, (self.key, str(value), interval))
  29. except Exception, e:
  30. if e.args[0]==1146:
  31. setup()
  32. self.set(value, interval)
  33. else: raise e
  34. def clear(self):
  35. """clear the item"""
  36. webnotes.conn.sql("delete from __CacheItem where `key`=%s", self.key)
  37. def setup():
  38. webnotes.conn.commit()
  39. webnotes.conn.sql("""create table __CacheItem(
  40. `key` VARCHAR(180) NOT NULL PRIMARY KEY,
  41. `value` TEXT,
  42. `expires_on` TIMESTAMP
  43. )""")
  44. webnotes.conn.begin()
  45. def get_item(key):
  46. """returns get CacheItem object"""
  47. return CacheItem(key)
  48. pass