You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

76 regels
2.4 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. """
  23. Simple Caching:
  24. Stores key-value pairs in database and enables simple caching
  25. CacheItem(key).get() returns the cached value if not expired (else returns null)
  26. CacheItem(key).set(interval = 60000) sets a value to cache, expiring after x seconds
  27. CahceItem(key).clear() clears an old value
  28. setup() sets up cache
  29. """
  30. import webnotes
  31. class CacheItem:
  32. def __init__(self, key):
  33. """create a new cache"""
  34. self.key = key
  35. def get(self):
  36. """get value"""
  37. try:
  38. return webnotes.conn.sql("select `value` from __CacheItem where `key`=%s and expires_on > NOW()", self.key)[0][0]
  39. except Exception:
  40. return None
  41. def set(self, value, interval=6000):
  42. """set a new value, with interval"""
  43. try:
  44. self.clear()
  45. webnotes.conn.sql("""INSERT INTO
  46. __CacheItem (`key`, `value`, expires_on)
  47. VALUES
  48. (%s, %s, addtime(now(), sec_to_time(%s)))
  49. """, (self.key, str(value), interval))
  50. except Exception, e:
  51. if e.args[0]==1146:
  52. setup()
  53. self.set(value, interval)
  54. else: raise e
  55. def clear(self):
  56. """clear the item"""
  57. webnotes.conn.sql("delete from __CacheItem where `key`=%s", self.key)
  58. def setup():
  59. webnotes.conn.commit()
  60. webnotes.conn.sql("""create table __CacheItem(
  61. `key` VARCHAR(180) NOT NULL PRIMARY KEY,
  62. `value` TEXT,
  63. `expires_on` TIMESTAMP
  64. )""")
  65. webnotes.conn.begin()