cache.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.contrib.cache
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. The main problem with dynamic Web sites is, well, they're dynamic. Each
  6. time a user requests a page, the webserver executes a lot of code, queries
  7. the database, renders templates until the visitor gets the page he sees.
  8. This is a lot more expensive than just loading a file from the file system
  9. and sending it to the visitor.
  10. For most Web applications, this overhead isn't a big deal but once it
  11. becomes, you will be glad to have a cache system in place.
  12. How Caching Works
  13. =================
  14. Caching is pretty simple. Basically you have a cache object lurking around
  15. somewhere that is connected to a remote cache or the file system or
  16. something else. When the request comes in you check if the current page
  17. is already in the cache and if so, you're returning it from the cache.
  18. Otherwise you generate the page and put it into the cache. (Or a fragment
  19. of the page, you don't have to cache the full thing)
  20. Here is a simple example of how to cache a sidebar for a template::
  21. def get_sidebar(user):
  22. identifier = 'sidebar_for/user%d' % user.id
  23. value = cache.get(identifier)
  24. if value is not None:
  25. return value
  26. value = generate_sidebar_for(user=user)
  27. cache.set(identifier, value, timeout=60 * 5)
  28. return value
  29. Creating a Cache Object
  30. =======================
  31. To create a cache object you just import the cache system of your choice
  32. from the cache module and instantiate it. Then you can start working
  33. with that object:
  34. >>> from werkzeug.contrib.cache import SimpleCache
  35. >>> c = SimpleCache()
  36. >>> c.set("foo", "value")
  37. >>> c.get("foo")
  38. 'value'
  39. >>> c.get("missing") is None
  40. True
  41. Please keep in mind that you have to create the cache and put it somewhere
  42. you have access to it (either as a module global you can import or you just
  43. put it into your WSGI application).
  44. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  45. :license: BSD, see LICENSE for more details.
  46. """
  47. import os
  48. import re
  49. import errno
  50. import tempfile
  51. from hashlib import md5
  52. from time import time
  53. try:
  54. import cPickle as pickle
  55. except ImportError: # pragma: no cover
  56. import pickle
  57. from werkzeug._compat import iteritems, string_types, text_type, \
  58. integer_types, to_native
  59. from werkzeug.posixemulation import rename
  60. def _items(mappingorseq):
  61. """Wrapper for efficient iteration over mappings represented by dicts
  62. or sequences::
  63. >>> for k, v in _items((i, i*i) for i in xrange(5)):
  64. ... assert k*k == v
  65. >>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
  66. ... assert k*k == v
  67. """
  68. if hasattr(mappingorseq, 'items'):
  69. return iteritems(mappingorseq)
  70. return mappingorseq
  71. class BaseCache(object):
  72. """Baseclass for the cache systems. All the cache systems implement this
  73. API or a superset of it.
  74. :param default_timeout: the default timeout (in seconds) that is used if no
  75. timeout is specified on :meth:`set`. A timeout of 0
  76. indicates that the cache never expires.
  77. """
  78. def __init__(self, default_timeout=300):
  79. self.default_timeout = default_timeout
  80. def get(self, key):
  81. """Look up key in the cache and return the value for it.
  82. :param key: the key to be looked up.
  83. :returns: The value if it exists and is readable, else ``None``.
  84. """
  85. return None
  86. def delete(self, key):
  87. """Delete `key` from the cache.
  88. :param key: the key to delete.
  89. :returns: Whether the key existed and has been deleted.
  90. :rtype: boolean
  91. """
  92. return True
  93. def get_many(self, *keys):
  94. """Returns a list of values for the given keys.
  95. For each key a item in the list is created::
  96. foo, bar = cache.get_many("foo", "bar")
  97. Has the same error handling as :meth:`get`.
  98. :param keys: The function accepts multiple keys as positional
  99. arguments.
  100. """
  101. return map(self.get, keys)
  102. def get_dict(self, *keys):
  103. """Like :meth:`get_many` but return a dict::
  104. d = cache.get_dict("foo", "bar")
  105. foo = d["foo"]
  106. bar = d["bar"]
  107. :param keys: The function accepts multiple keys as positional
  108. arguments.
  109. """
  110. return dict(zip(keys, self.get_many(*keys)))
  111. def set(self, key, value, timeout=None):
  112. """Add a new key/value to the cache (overwrites value, if key already
  113. exists in the cache).
  114. :param key: the key to set
  115. :param value: the value for the key
  116. :param timeout: the cache timeout for the key (if not specified,
  117. it uses the default timeout). A timeout of 0 idicates
  118. that the cache never expires.
  119. :returns: ``True`` if key has been updated, ``False`` for backend
  120. errors. Pickling errors, however, will raise a subclass of
  121. ``pickle.PickleError``.
  122. :rtype: boolean
  123. """
  124. return True
  125. def add(self, key, value, timeout=None):
  126. """Works like :meth:`set` but does not overwrite the values of already
  127. existing keys.
  128. :param key: the key to set
  129. :param value: the value for the key
  130. :param timeout: the cache timeout for the key or the default
  131. timeout if not specified. A timeout of 0 indicates
  132. that the cache never expires.
  133. :returns: Same as :meth:`set`, but also ``False`` for already
  134. existing keys.
  135. :rtype: boolean
  136. """
  137. return True
  138. def set_many(self, mapping, timeout=None):
  139. """Sets multiple keys and values from a mapping.
  140. :param mapping: a mapping with the keys/values to set.
  141. :param timeout: the cache timeout for the key (if not specified,
  142. it uses the default timeout). A timeout of 0
  143. indicates tht the cache never expires.
  144. :returns: Whether all given keys have been set.
  145. :rtype: boolean
  146. """
  147. rv = True
  148. for key, value in _items(mapping):
  149. if not self.set(key, value, timeout):
  150. rv = False
  151. return rv
  152. def delete_many(self, *keys):
  153. """Deletes multiple keys at once.
  154. :param keys: The function accepts multiple keys as positional
  155. arguments.
  156. :returns: Whether all given keys have been deleted.
  157. :rtype: boolean
  158. """
  159. return all(self.delete(key) for key in keys)
  160. def has(self, key):
  161. """Checks if a key exists in the cache without returning it. This is a
  162. cheap operation that bypasses loading the actual data on the backend.
  163. This method is optional and may not be implemented on all caches.
  164. :param key: the key to check
  165. """
  166. raise NotImplementedError(
  167. '%s doesn\'t have an efficient implementation of `has`. That '
  168. 'means it is impossible to check whether a key exists without '
  169. 'fully loading the key\'s data. Consider using `self.get` '
  170. 'explicitly if you don\'t care about performance.'
  171. )
  172. def clear(self):
  173. """Clears the cache. Keep in mind that not all caches support
  174. completely clearing the cache.
  175. :returns: Whether the cache has been cleared.
  176. :rtype: boolean
  177. """
  178. return True
  179. def inc(self, key, delta=1):
  180. """Increments the value of a key by `delta`. If the key does
  181. not yet exist it is initialized with `delta`.
  182. For supporting caches this is an atomic operation.
  183. :param key: the key to increment.
  184. :param delta: the delta to add.
  185. :returns: The new value or ``None`` for backend errors.
  186. """
  187. value = (self.get(key) or 0) + delta
  188. return value if self.set(key, value) else None
  189. def dec(self, key, delta=1):
  190. """Decrements the value of a key by `delta`. If the key does
  191. not yet exist it is initialized with `-delta`.
  192. For supporting caches this is an atomic operation.
  193. :param key: the key to increment.
  194. :param delta: the delta to subtract.
  195. :returns: The new value or `None` for backend errors.
  196. """
  197. value = (self.get(key) or 0) - delta
  198. return value if self.set(key, value) else None
  199. class NullCache(BaseCache):
  200. """A cache that doesn't cache. This can be useful for unit testing.
  201. :param default_timeout: a dummy parameter that is ignored but exists
  202. for API compatibility with other caches.
  203. """
  204. class SimpleCache(BaseCache):
  205. """Simple memory cache for single process environments. This class exists
  206. mainly for the development server and is not 100% thread safe. It tries
  207. to use as many atomic operations as possible and no locks for simplicity
  208. but it could happen under heavy load that keys are added multiple times.
  209. :param threshold: the maximum number of items the cache stores before
  210. it starts deleting some.
  211. :param default_timeout: the default timeout that is used if no timeout is
  212. specified on :meth:`~BaseCache.set`. A timeout of
  213. 0 indicates that the cache never expires.
  214. """
  215. def __init__(self, threshold=500, default_timeout=300):
  216. BaseCache.__init__(self, default_timeout)
  217. self._cache = {}
  218. self.clear = self._cache.clear
  219. self._threshold = threshold
  220. def _prune(self):
  221. if len(self._cache) > self._threshold:
  222. now = time()
  223. toremove = []
  224. for idx, (key, (expires, _)) in enumerate(self._cache.items()):
  225. if (expires != 0 and expires <= now) or idx % 3 == 0:
  226. toremove.append(key)
  227. for key in toremove:
  228. self._cache.pop(key, None)
  229. def _get_expiration(self, timeout):
  230. if timeout is None:
  231. timeout = self.default_timeout
  232. if timeout > 0:
  233. timeout = time() + timeout
  234. return timeout
  235. def get(self, key):
  236. try:
  237. expires, value = self._cache[key]
  238. if expires == 0 or expires > time():
  239. return pickle.loads(value)
  240. except (KeyError, pickle.PickleError):
  241. return None
  242. def set(self, key, value, timeout=None):
  243. expires = self._get_expiration(timeout)
  244. self._prune()
  245. self._cache[key] = (expires, pickle.dumps(value,
  246. pickle.HIGHEST_PROTOCOL))
  247. return True
  248. def add(self, key, value, timeout=None):
  249. expires = self._get_expiration(timeout)
  250. self._prune()
  251. item = (expires, pickle.dumps(value,
  252. pickle.HIGHEST_PROTOCOL))
  253. if key in self._cache:
  254. return False
  255. self._cache.setdefault(key, item)
  256. return True
  257. def delete(self, key):
  258. return self._cache.pop(key, None) is not None
  259. def has(self, key):
  260. try:
  261. expires, value = self._cache[key]
  262. return expires == 0 or expires > time()
  263. except KeyError:
  264. return False
  265. _test_memcached_key = re.compile(r'[^\x00-\x21\xff]{1,250}$').match
  266. class MemcachedCache(BaseCache):
  267. """A cache that uses memcached as backend.
  268. The first argument can either be an object that resembles the API of a
  269. :class:`memcache.Client` or a tuple/list of server addresses. In the
  270. event that a tuple/list is passed, Werkzeug tries to import the best
  271. available memcache library.
  272. This cache looks into the following packages/modules to find bindings for
  273. memcached:
  274. - ``pylibmc``
  275. - ``google.appengine.api.memcached``
  276. - ``memcached``
  277. Implementation notes: This cache backend works around some limitations in
  278. memcached to simplify the interface. For example unicode keys are encoded
  279. to utf-8 on the fly. Methods such as :meth:`~BaseCache.get_dict` return
  280. the keys in the same format as passed. Furthermore all get methods
  281. silently ignore key errors to not cause problems when untrusted user data
  282. is passed to the get methods which is often the case in web applications.
  283. :param servers: a list or tuple of server addresses or alternatively
  284. a :class:`memcache.Client` or a compatible client.
  285. :param default_timeout: the default timeout that is used if no timeout is
  286. specified on :meth:`~BaseCache.set`. A timeout of
  287. 0 indicates taht the cache never expires.
  288. :param key_prefix: a prefix that is added before all keys. This makes it
  289. possible to use the same memcached server for different
  290. applications. Keep in mind that
  291. :meth:`~BaseCache.clear` will also clear keys with a
  292. different prefix.
  293. """
  294. def __init__(self, servers=None, default_timeout=300, key_prefix=None):
  295. BaseCache.__init__(self, default_timeout)
  296. if servers is None or isinstance(servers, (list, tuple)):
  297. if servers is None:
  298. servers = ['127.0.0.1:11211']
  299. self._client = self.import_preferred_memcache_lib(servers)
  300. if self._client is None:
  301. raise RuntimeError('no memcache module found')
  302. else:
  303. # NOTE: servers is actually an already initialized memcache
  304. # client.
  305. self._client = servers
  306. self.key_prefix = to_native(key_prefix)
  307. def _normalize_key(self, key):
  308. key = to_native(key, 'utf-8')
  309. if self.key_prefix:
  310. key = self.key_prefix + key
  311. return key
  312. def _normalize_timeout(self, timeout):
  313. if timeout is None:
  314. timeout = self.default_timeout
  315. if timeout > 0:
  316. timeout = int(time()) + timeout
  317. return timeout
  318. def get(self, key):
  319. key = self._normalize_key(key)
  320. # memcached doesn't support keys longer than that. Because often
  321. # checks for so long keys can occur because it's tested from user
  322. # submitted data etc we fail silently for getting.
  323. if _test_memcached_key(key):
  324. return self._client.get(key)
  325. def get_dict(self, *keys):
  326. key_mapping = {}
  327. have_encoded_keys = False
  328. for key in keys:
  329. encoded_key = self._normalize_key(key)
  330. if not isinstance(key, str):
  331. have_encoded_keys = True
  332. if _test_memcached_key(key):
  333. key_mapping[encoded_key] = key
  334. d = rv = self._client.get_multi(key_mapping.keys())
  335. if have_encoded_keys or self.key_prefix:
  336. rv = {}
  337. for key, value in iteritems(d):
  338. rv[key_mapping[key]] = value
  339. if len(rv) < len(keys):
  340. for key in keys:
  341. if key not in rv:
  342. rv[key] = None
  343. return rv
  344. def add(self, key, value, timeout=None):
  345. key = self._normalize_key(key)
  346. timeout = self._normalize_timeout(timeout)
  347. return self._client.add(key, value, timeout)
  348. def set(self, key, value, timeout=None):
  349. key = self._normalize_key(key)
  350. timeout = self._normalize_timeout(timeout)
  351. return self._client.set(key, value, timeout)
  352. def get_many(self, *keys):
  353. d = self.get_dict(*keys)
  354. return [d[key] for key in keys]
  355. def set_many(self, mapping, timeout=None):
  356. new_mapping = {}
  357. for key, value in _items(mapping):
  358. key = self._normalize_key(key)
  359. new_mapping[key] = value
  360. timeout = self._normalize_timeout(timeout)
  361. failed_keys = self._client.set_multi(new_mapping, timeout)
  362. return not failed_keys
  363. def delete(self, key):
  364. key = self._normalize_key(key)
  365. if _test_memcached_key(key):
  366. return self._client.delete(key)
  367. def delete_many(self, *keys):
  368. new_keys = []
  369. for key in keys:
  370. key = self._normalize_key(key)
  371. if _test_memcached_key(key):
  372. new_keys.append(key)
  373. return self._client.delete_multi(new_keys)
  374. def has(self, key):
  375. key = self._normalize_key(key)
  376. if _test_memcached_key(key):
  377. return self._client.append(key, '')
  378. return False
  379. def clear(self):
  380. return self._client.flush_all()
  381. def inc(self, key, delta=1):
  382. key = self._normalize_key(key)
  383. return self._client.incr(key, delta)
  384. def dec(self, key, delta=1):
  385. key = self._normalize_key(key)
  386. return self._client.decr(key, delta)
  387. def import_preferred_memcache_lib(self, servers):
  388. """Returns an initialized memcache client. Used by the constructor."""
  389. try:
  390. import pylibmc
  391. except ImportError:
  392. pass
  393. else:
  394. return pylibmc.Client(servers)
  395. try:
  396. from google.appengine.api import memcache
  397. except ImportError:
  398. pass
  399. else:
  400. return memcache.Client()
  401. try:
  402. import memcache
  403. except ImportError:
  404. pass
  405. else:
  406. return memcache.Client(servers)
  407. # backwards compatibility
  408. GAEMemcachedCache = MemcachedCache
  409. class RedisCache(BaseCache):
  410. """Uses the Redis key-value store as a cache backend.
  411. The first argument can be either a string denoting address of the Redis
  412. server or an object resembling an instance of a redis.Redis class.
  413. Note: Python Redis API already takes care of encoding unicode strings on
  414. the fly.
  415. .. versionadded:: 0.7
  416. .. versionadded:: 0.8
  417. `key_prefix` was added.
  418. .. versionchanged:: 0.8
  419. This cache backend now properly serializes objects.
  420. .. versionchanged:: 0.8.3
  421. This cache backend now supports password authentication.
  422. .. versionchanged:: 0.10
  423. ``**kwargs`` is now passed to the redis object.
  424. :param host: address of the Redis server or an object which API is
  425. compatible with the official Python Redis client (redis-py).
  426. :param port: port number on which Redis server listens for connections.
  427. :param password: password authentication for the Redis server.
  428. :param db: db (zero-based numeric index) on Redis Server to connect.
  429. :param default_timeout: the default timeout that is used if no timeout is
  430. specified on :meth:`~BaseCache.set`. A timeout of
  431. 0 indicates that the cache never expires.
  432. :param key_prefix: A prefix that should be added to all keys.
  433. Any additional keyword arguments will be passed to ``redis.Redis``.
  434. """
  435. def __init__(self, host='localhost', port=6379, password=None,
  436. db=0, default_timeout=300, key_prefix=None, **kwargs):
  437. BaseCache.__init__(self, default_timeout)
  438. if isinstance(host, string_types):
  439. try:
  440. import redis
  441. except ImportError:
  442. raise RuntimeError('no redis module found')
  443. if kwargs.get('decode_responses', None):
  444. raise ValueError('decode_responses is not supported by '
  445. 'RedisCache.')
  446. self._client = redis.Redis(host=host, port=port, password=password,
  447. db=db, **kwargs)
  448. else:
  449. self._client = host
  450. self.key_prefix = key_prefix or ''
  451. def _get_expiration(self, timeout):
  452. if timeout is None:
  453. timeout = self.default_timeout
  454. if timeout == 0:
  455. timeout = -1
  456. return timeout
  457. def dump_object(self, value):
  458. """Dumps an object into a string for redis. By default it serializes
  459. integers as regular string and pickle dumps everything else.
  460. """
  461. t = type(value)
  462. if t in integer_types:
  463. return str(value).encode('ascii')
  464. return b'!' + pickle.dumps(value)
  465. def load_object(self, value):
  466. """The reversal of :meth:`dump_object`. This might be called with
  467. None.
  468. """
  469. if value is None:
  470. return None
  471. if value.startswith(b'!'):
  472. try:
  473. return pickle.loads(value[1:])
  474. except pickle.PickleError:
  475. return None
  476. try:
  477. return int(value)
  478. except ValueError:
  479. # before 0.8 we did not have serialization. Still support that.
  480. return value
  481. def get(self, key):
  482. return self.load_object(self._client.get(self.key_prefix + key))
  483. def get_many(self, *keys):
  484. if self.key_prefix:
  485. keys = [self.key_prefix + key for key in keys]
  486. return [self.load_object(x) for x in self._client.mget(keys)]
  487. def set(self, key, value, timeout=None):
  488. timeout = self._get_expiration(timeout)
  489. dump = self.dump_object(value)
  490. if timeout == -1:
  491. result = self._client.set(name=self.key_prefix + key,
  492. value=dump)
  493. else:
  494. result = self._client.setex(name=self.key_prefix + key,
  495. value=dump, time=timeout)
  496. return result
  497. def add(self, key, value, timeout=None):
  498. timeout = self._get_expiration(timeout)
  499. dump = self.dump_object(value)
  500. return (
  501. self._client.setnx(name=self.key_prefix + key, value=dump) and
  502. self._client.expire(name=self.key_prefix + key, time=timeout)
  503. )
  504. def set_many(self, mapping, timeout=None):
  505. timeout = self._get_expiration(timeout)
  506. # Use transaction=False to batch without calling redis MULTI
  507. # which is not supported by twemproxy
  508. pipe = self._client.pipeline(transaction=False)
  509. for key, value in _items(mapping):
  510. dump = self.dump_object(value)
  511. if timeout == -1:
  512. pipe.set(name=self.key_prefix + key, value=dump)
  513. else:
  514. pipe.setex(name=self.key_prefix + key, value=dump,
  515. time=timeout)
  516. return pipe.execute()
  517. def delete(self, key):
  518. return self._client.delete(self.key_prefix + key)
  519. def delete_many(self, *keys):
  520. if not keys:
  521. return
  522. if self.key_prefix:
  523. keys = [self.key_prefix + key for key in keys]
  524. return self._client.delete(*keys)
  525. def has(self, key):
  526. return self._client.exists(self.key_prefix + key)
  527. def clear(self):
  528. status = False
  529. if self.key_prefix:
  530. keys = self._client.keys(self.key_prefix + '*')
  531. if keys:
  532. status = self._client.delete(*keys)
  533. else:
  534. status = self._client.flushdb()
  535. return status
  536. def inc(self, key, delta=1):
  537. return self._client.incr(name=self.key_prefix + key, amount=delta)
  538. def dec(self, key, delta=1):
  539. return self._client.decr(name=self.key_prefix + key, amount=delta)
  540. class FileSystemCache(BaseCache):
  541. """A cache that stores the items on the file system. This cache depends
  542. on being the only user of the `cache_dir`. Make absolutely sure that
  543. nobody but this cache stores files there or otherwise the cache will
  544. randomly delete files therein.
  545. :param cache_dir: the directory where cache files are stored.
  546. :param threshold: the maximum number of items the cache stores before
  547. it starts deleting some.
  548. :param default_timeout: the default timeout that is used if no timeout is
  549. specified on :meth:`~BaseCache.set`. A timeout of
  550. 0 indicates that the cache never expires.
  551. :param mode: the file mode wanted for the cache files, default 0600
  552. """
  553. #: used for temporary files by the FileSystemCache
  554. _fs_transaction_suffix = '.__wz_cache'
  555. def __init__(self, cache_dir, threshold=500, default_timeout=300,
  556. mode=0o600):
  557. BaseCache.__init__(self, default_timeout)
  558. self._path = cache_dir
  559. self._threshold = threshold
  560. self._mode = mode
  561. try:
  562. os.makedirs(self._path)
  563. except OSError as ex:
  564. if ex.errno != errno.EEXIST:
  565. raise
  566. def _list_dir(self):
  567. """return a list of (fully qualified) cache filenames
  568. """
  569. return [os.path.join(self._path, fn) for fn in os.listdir(self._path)
  570. if not fn.endswith(self._fs_transaction_suffix)]
  571. def _prune(self):
  572. entries = self._list_dir()
  573. if len(entries) > self._threshold:
  574. now = time()
  575. try:
  576. for idx, fname in enumerate(entries):
  577. remove = False
  578. with open(fname, 'rb') as f:
  579. expires = pickle.load(f)
  580. remove = (expires != 0 and expires <= now) or idx % 3 == 0
  581. if remove:
  582. os.remove(fname)
  583. except (IOError, OSError):
  584. pass
  585. def clear(self):
  586. for fname in self._list_dir():
  587. try:
  588. os.remove(fname)
  589. except (IOError, OSError):
  590. return False
  591. return True
  592. def _get_filename(self, key):
  593. if isinstance(key, text_type):
  594. key = key.encode('utf-8') # XXX unicode review
  595. hash = md5(key).hexdigest()
  596. return os.path.join(self._path, hash)
  597. def get(self, key):
  598. filename = self._get_filename(key)
  599. try:
  600. with open(filename, 'rb') as f:
  601. pickle_time = pickle.load(f)
  602. if pickle_time == 0 or pickle_time >= time():
  603. return pickle.load(f)
  604. else:
  605. os.remove(filename)
  606. return None
  607. except (IOError, OSError, pickle.PickleError):
  608. return None
  609. def add(self, key, value, timeout=None):
  610. filename = self._get_filename(key)
  611. if not os.path.exists(filename):
  612. return self.set(key, value, timeout)
  613. return False
  614. def set(self, key, value, timeout=None):
  615. if timeout is None:
  616. timeout = int(time() + self.default_timeout)
  617. elif timeout != 0:
  618. timeout = int(time() + timeout)
  619. filename = self._get_filename(key)
  620. self._prune()
  621. try:
  622. fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
  623. dir=self._path)
  624. with os.fdopen(fd, 'wb') as f:
  625. pickle.dump(timeout, f, 1)
  626. pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
  627. rename(tmp, filename)
  628. os.chmod(filename, self._mode)
  629. except (IOError, OSError):
  630. return False
  631. else:
  632. return True
  633. def delete(self, key):
  634. try:
  635. os.remove(self._get_filename(key))
  636. except (IOError, OSError):
  637. return False
  638. else:
  639. return True
  640. def has(self, key):
  641. filename = self._get_filename(key)
  642. try:
  643. with open(filename, 'rb') as f:
  644. pickle_time = pickle.load(f)
  645. if pickle_time == 0 or pickle_time >= time():
  646. return True
  647. else:
  648. os.remove(filename)
  649. return False
  650. except (IOError, OSError, pickle.PickleError):
  651. return False