File: SimpleCache.py

package info (click to toggle)
zope-ldapuserfolder 2.2-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 508 kB
  • ctags: 313
  • sloc: python: 3,042; sh: 50; makefile: 38
file content (79 lines) | stat: -rw-r--r-- 1,909 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#####################################################################
#
# SimpleCache     A simple non-persistent cache
#
# This software is governed by a license. See
# LICENSE.txt for the terms of this license.
#
#####################################################################

import time

class SimpleCache:
    """ A simple non-persistent cache """

    def __init__(self):
        """ Initialize a new instance """
        self.cache = {}
        self.timeout = 600


    def set(self, id, object):
        """ Cache an object under the given id """
        id = id.lower()
        self.cache[id] = object


    def get(self, id, password=None):
        """ Retrieve a cached object if it is valid """
        try:
            id = id.lower()
        except AttributeError:
            return None

        user = self.cache.get(id, None)

        if ( password is not None and 
             user is not None and 
             password != user._getPassword() ):
            user = None

        if ( user and 
             (time.time() < user.getCreationTime().timeTime() + self.timeout) ):
            return user
        else:
            return None


    def getCache(self):
        """ Get valid cache records """
        valid = []
        cached = self.cache.values()
        now = time.time()

        for object in cached:
            created = object.getCreationTime().timeTime()
            if object and now < (created + self.timeout):
                valid.append(object)

        return valid


    def remove(self, id):
        """ Purge a record out of the cache """
        id = id.lower()

        if self.cache.has_key(id):
            del self.cache[id]


    def clear(self):
        """ Clear the internal caches """
        self.cache = {}


    def setTimeout(self, timeout):
        """ Set the timeout (in seconds) for cached entries """
        self.timeout = timeout