def testTouch(self):
        timedDict = TimedDictionary(TWO_HOURS)
        timedDict[1] = SomeObject('id1')
        timedDict[2] = SomeObject('id2')

        self.assertEquals([1, 2], timedDict._expirationOrder)
        timedDict.touch(1)
        self.assertEquals([2, 1], timedDict._expirationOrder)
    def testTouch(self):
        timedDict = TimedDictionary(TWO_HOURS)
        timedDict[1] = SomeObject('id1')
        timedDict[2] = SomeObject('id2')

        self.assertEqual([1, 2], timedDict._expirationOrder)
        timedDict.touch(1)
        self.assertEqual([2, 1], timedDict._expirationOrder)
Beispiel #3
0
class CookieMemoryStore(object):
    def __init__(self, timeout, name=None, secure=False, httpOnly=False):
        self._timeout = timeout
        self._store = TimedDictionary(self._timeout)
        self._name = '{0}{1}'.format('' if name is None else '%s-' % name,
                                     uuid4())
        self._secure = secure
        self._httpOnly = httpOnly

    def createCookie(self, anObject):
        cookie = str(uuid4())
        cookieValues = dict(value=anObject)
        cookieValues[SECURE] = self._secure
        cookieValues[HTTPONLY] = self._httpOnly
        self._store[cookie] = cookieValues
        return self._result(cookie)

    def removeCookie(self, cookie):
        try:
            del self._store[cookie]
        except KeyError:
            pass

    def removeCookies(self, filter):
        for k in self._store.keys():
            try:
                if filter(self._store.peek(k)['value']):
                    del self._store[k]
            except (AttributeError, KeyError):
                pass

    def validateCookie(self, cookie):
        cookieInfo = self._store.get(cookie)
        if cookieInfo is not None and cookieInfo['value'] is not None:
            self._store.touch(cookie)
            return self._result(cookie)
        return None

    def cookieName(self):
        return self._name

    def _result(self, cookie):
        cookieInfo = self._store.get(cookie)
        values = [
            "{0}={1}".format(*i) for i in [(self._name, cookie), (
                'path',
                '/'), ('expires', formatdate(self._now() + self._timeout))]
        ]
        values.extend(k for k in [SECURE, HTTPONLY]
                      if cookieInfo.get(k) == True)

        return dict(cookie=cookie,
                    value=cookieInfo['value'],
                    header='Set-Cookie: {0}'.format('; '.join(values)))

    def _now(self):
        return time()
    def testPurge(self):
        timedDict = TimedDictionary(TWO_HOURS)
        timedDict[1] = SomeObject('id1')
        timedDict[2] = SomeObject('id2')
        timedDict._now = lambda : time() + ONE_HOUR
        self.assertEquals([1, 2], timedDict._expirationOrder)

        timedDict[3] = SomeObject('id3')
        timedDict.touch(2)
        timedDict._now = lambda : time() + TWO_HOURS
        timedDict.purge()
        self.assertEquals([3, 2], timedDict._expirationOrder)
        timedDict._now = lambda : time() + TWO_HOURS + TWO_HOURS
        timedDict.purge()
        self.assertEquals([], timedDict._expirationOrder)
    def testPurge(self):
        timedDict = TimedDictionary(TWO_HOURS)
        timedDict[1] = SomeObject('id1')
        timedDict[2] = SomeObject('id2')
        timedDict._now = lambda: time() + ONE_HOUR
        self.assertEqual([1, 2], timedDict._expirationOrder)

        timedDict[3] = SomeObject('id3')
        timedDict.touch(2)
        timedDict._now = lambda: time() + TWO_HOURS
        timedDict.purge()
        self.assertEqual([3, 2], timedDict._expirationOrder)
        timedDict._now = lambda: time() + TWO_HOURS + TWO_HOURS
        timedDict.purge()
        self.assertEqual([], timedDict._expirationOrder)
Beispiel #6
0
class CookieMemoryStore(object):
    def __init__(self, timeout, name=None):
        self._timeout = timeout
        self._store = TimedDictionary(self._timeout)
        self._name = '{0}{1}'.format('' if name is None else '%s-' % name, uuid4())

    def createCookie(self, anObject):
        cookie = str(uuid4())
        self._store[cookie] = anObject
        return self._result(cookie, anObject)

    def removeCookie(self, cookie):
        try:
            del self._store[cookie]
        except KeyError:
            pass

    def removeCookies(self, filter):
        for k in self._store.keys():
            try:
                if filter(self._store.peek(k)):
                    del self._store[k]
            except (AttributeError, KeyError):
                pass

    def validateCookie(self, cookie):
        anObject = self._store.get(cookie)
        if anObject is not None:
            self._store.touch(cookie)
            return self._result(cookie, anObject)
        return None

    def cookieName(self):
        return self._name

    def _result(self, cookie, anObject):
        return dict(
            cookie=cookie,
            value=anObject,
            header='Set-Cookie: {0}={1}; path=/; expires={2}'.format(
                self._name,
                cookie,
                formatdate(self._now() + self._timeout)))


    def _now(self):
        return time()
Beispiel #7
0
class FlagCheck(Observable):
    def __init__(self, serviceIdentifier, flag, name=None):
        Observable.__init__(self, name=name)
        self._serviceIdentifier = serviceIdentifier
        self._flag = flag
        self._flagSet = flag.default
        self._seed = randomWord(20)
        self._cookiekey = 'flagcheck%s=' % randomWord(10)
        self._debugTimeout = 60
        self._debugIds = TimedDictionary(self._debugTimeout)

    def updateConfig(self, this_service=None, **kwargs):
        state = {} if this_service is None else this_service.get('state', {})
        self._flagSet = self._flag.isSet(state)
        return
        yield

    def handleRequest(self, arguments, Headers, **kwargs):
        debugId = self._getDebugId(Headers)
        debug = arguments.pop('debug', [None])[0] is not None or debugId
        if not debug:
            try:
                self._check(message='handleRequest')
                yield self.all.handleRequest(arguments=arguments, Headers=Headers, **kwargs)
            except EnvironmentError:
                yield 'HTTP/1.0 503 Service Temporarily Unavailable\r\n\r\n'
        else:
            debugId = self._registerDebugId(debugId=debugId, **kwargs)
            yield insertHeader(
                    compose(self.all.handleRequest(arguments=arguments, Headers=Headers, **kwargs)),
                    extraHeader='Set-Cookie: '+'; '.join([
                            self._cookiekey+debugId,
                            'Expires={0}'.format(self._zulutime().add(seconds=2*self._debugTimeout).rfc1123()),
                        ])
                )

    def _zulutime(self):
        return ZuluTime()

    def _getDebugId(self, Headers):
        debugIds = [cookie.split(self._cookiekey)[-1].strip() for cookie in Headers.get('Cookie','').split(';') if cookie.strip().startswith(self._cookiekey)]
        if len(debugIds) == 1:
            return self._debugIds.get(debugIds[0])
        return None

    def _registerDebugId(self, debugId, Client, **ignored):
        if debugId is None:
            clientaddress, ignoredPort = Client
            debugId = sha1('%s%s%s%s' % (time(), randomWord(10), clientaddress, self._seed)).hexdigest()
            self._debugIds[debugId] = debugId
        else:
            self._debugIds.touch(debugId)
        return debugId

    def all_unknown(self, message, **kwargs):
        self._check(message=message)
        yield self.all.unknown(message, **kwargs)

    def _check(self, message):
        if not self._flagSet:
            raise EnvironmentError("'%s' is not allowed at the moment (%s=False)." % (message, self._flag))