@@ -163,7 +163,6 @@ class RedirectLimit(Exception):
163
163
164
164
165
165
CHUNK_SIZE = 1024 * 8
166
- CACHE_SIZE = 10 , 75 # some random values to limit memory use
167
166
168
167
def cache_sort (i ):
169
168
t = time .mktime (time .strptime (i [1 ][1 ]['Date' ][5 :- 4 ], '%d %b %Y %H:%M:%S' ))
@@ -227,8 +226,17 @@ def __init__(self, cache=None, timeout=None, max_redirects=5,
227
226
"""
228
227
from couchdb import __version__ as VERSION
229
228
self .user_agent = 'CouchDB-Python/%s' % VERSION
230
- if cache is None :
231
- cache = {}
229
+ # XXX We accept a `cache` dict arg, but the ref gets overwritten later
230
+ # during cache cleanup. Do we remove the cache arg (does using a shared
231
+ # Session instance cover the same use cases?) or fix the cache cleanup?
232
+ # For now, let's just assign the dict to the Cache instance to retain
233
+ # current behaviour.
234
+ if cache is not None :
235
+ cache_by_url = cache
236
+ cache = Cache ()
237
+ cache .by_url = cache_by_url
238
+ else :
239
+ cache = Cache ()
232
240
self .cache = cache
233
241
self .max_redirects = max_redirects
234
242
self .perm_redirects = {}
@@ -331,7 +339,7 @@ def _try_request():
331
339
data = StringIO (data )
332
340
return status , msg , data
333
341
elif cached_resp :
334
- del self .cache [ url ]
342
+ self .cache . remove ( url )
335
343
336
344
# Handle redirects
337
345
if status == 303 or \
@@ -394,18 +402,37 @@ def _try_request():
394
402
395
403
# Store cachable responses
396
404
if not streamed and method == 'GET' and 'etag' in resp .msg :
397
- self .cache [url ] = (status , resp .msg , data )
398
- if len (self .cache ) > CACHE_SIZE [1 ]:
399
- self ._clean_cache ()
405
+ self .cache .put (url , (status , resp .msg , data ))
400
406
401
407
if not streamed and data is not None :
402
408
data = StringIO (data )
403
409
404
410
return status , resp .msg , data
405
411
406
- def _clean_cache (self ):
407
- ls = sorted (self .cache .iteritems (), key = cache_sort )
408
- self .cache = dict (ls [- CACHE_SIZE [0 ]:])
412
+
413
+ class Cache (object ):
414
+ """Content cache."""
415
+
416
+ # Some random values to limit memory use
417
+ keep_size , max_size = 10 , 75
418
+
419
+ def __init__ (self ):
420
+ self .by_url = {}
421
+
422
+ def get (self , url ):
423
+ return self .by_url .get (url )
424
+
425
+ def put (self , url , response ):
426
+ self .by_url [url ] = response
427
+ if len (self .by_url ) > self .max_size :
428
+ self ._clean ()
429
+
430
+ def remove (self , url ):
431
+ del self .by_url [url ]
432
+
433
+ def _clean (self ):
434
+ ls = sorted (self .by_url .iteritems (), key = cache_sort )
435
+ self .by_url = dict (ls [- self .keep_size :])
409
436
410
437
411
438
class ConnectionPool (object ):
0 commit comments