コード例 #1
0
    def __init__(self,
                 request,
                 key='beaker.session.id',
                 timeout=None,
                 cookie_expires=True,
                 cookie_domain=None,
                 encrypt_key=None,
                 validate_key=None,
                 secure=False,
                 **kwargs):

        if not crypto.has_aes and encrypt_key:
            raise InvalidCryptoBackendError(
                "No AES library is installed, can't generate "
                "encrypted cookie-only Session.")

        self.request = request
        self.key = key
        self.timeout = timeout
        self.cookie_expires = cookie_expires
        self.encrypt_key = encrypt_key
        self.validate_key = validate_key
        self.request['set_cookie'] = False
        self.secure = secure
        self._domain = cookie_domain
        self._path = '/'

        try:
            cookieheader = request['cookie']
        except KeyError:
            cookieheader = ''

        if validate_key is None:
            raise BeakerException("No validate_key specified for Cookie only "
                                  "Session.")

        try:
            self.cookie = SignedCookie(validate_key, input=cookieheader)
        except Cookie.CookieError:
            self.cookie = SignedCookie(validate_key, input=None)

        self['_id'] = self._make_id()
        self.is_new = True

        # If we have a cookie, load it
        if self.key in self.cookie and self.cookie[self.key].value is not None:
            self.is_new = False
            try:
                self.update(self._decrypt_data())
            except:
                pass
            if self.timeout is not None and time.time() - \
               self['_accessed_time'] > self.timeout:
                self.clear()
            self.accessed_dict = self.copy()
            self._create_cookie()
コード例 #2
0
    def region_invalidate(self, namespace, region, *args):
        """Invalidate a cache region namespace or decorated function
        
        This function only invalidates cache spaces created with the
        cache_region decorator.
        
        :param namespace: Either the namespace of the result to invalidate, or the
           name of the cached function
        
        :param region: The region the function was cached to. If the function was
            cached to a single region then this argument can be None
        
        :param args: Arguments that were used to differentiate the cached
            function as well as the arguments passed to the decorated
            function

        Example::
            
            # Assuming a cache object is available like:
            cache = CacheManager(dict_of_config_options)
            
            def populate_things(invalidate=False):
                
                @cache.region('short_term', 'some_data')
                def load(search_term, limit, offset):
                    return load_the_data(search_term, limit, offset)
                
                # If the results should be invalidated first
                if invalidate:
                    cache.region_invalidate(load, None, 'some_data',
                                            'rabbits', 20, 0)
                return load('rabbits', 20, 0)
            
        
        """
        return region_invalidate(namespace, region, *args)
        if callable(namespace):
            if not region:
                region = namespace._arg_region
            namespace = namespace._arg_namespace

        if not region:
            raise BeakerException("Region or callable function "
                                  "namespace is required")
        else:
            region = self.regions[region]

        cache = self.get_cache(namespace, **region)
        cache_key = " ".join(str(x) for x in args)
        cache.remove_value(cache_key)
コード例 #3
0
        def cached(*args):
            reg = cache_regions[region]
            if not reg.get('enabled', True):
                return func(*args)

            if not cache[0]:
                if region not in cache_regions:
                    raise BeakerException('Cache region not configured: %s' %
                                          region)
                cache[0] = Cache._get_cache(namespace, reg)

            cache_key = " ".join(map(str, deco_args + args))

            def go():
                return func(*args)

            return cache[0].get_value(cache_key, createfunc=go)
コード例 #4
0
    def _create_cookie(self):
        if '_creation_time' not in self:
            self['_creation_time'] = time.time()
        if '_id' not in self:
            self['_id'] = self._make_id()
        self['_accessed_time'] = time.time()

        if self.cookie_expires is not True:
            if self.cookie_expires is False:
                expires = datetime.fromtimestamp(0x7FFFFFFF)
            elif isinstance(self.cookie_expires, timedelta):
                expires = datetime.today() + self.cookie_expires
            elif isinstance(self.cookie_expires, datetime):
                expires = self.cookie_expires
            else:
                raise ValueError("Invalid argument for cookie_expires: %s" %
                                 repr(self.cookie_expires))
            self['_expires'] = expires
        elif '_expires' in self:
            expires = self['_expires']
        else:
            expires = None

        val = self._encrypt_data()
        if len(val) > 4064:
            raise BeakerException("Cookie value is too long to store")

        self.cookie[self.key] = val
        if '_domain' in self:
            self.cookie[self.key]['domain'] = self['_domain']
        elif self._domain:
            self.cookie[self.key]['domain'] = self._domain
        if self.secure:
            self.cookie[self.key]['secure'] = True

        self.cookie[self.key]['path'] = self.get('_path', '/')

        if expires:
            self.cookie[self.key]['expires'] = \
                expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )
        self.request['cookie_out'] = self.cookie[self.key].output(header='')
        self.request['set_cookie'] = True
コード例 #5
0
 def get_cache_region(self, name, region):
     if region not in self.regions:
         raise BeakerException('Cache region not configured: %s' % region)
     kw = self.regions[region]
     return Cache._get_cache(name, kw)
コード例 #6
0
}

# Initialize the cache region dict
cache_regions = {}
cache_managers = {}

try:
    import pkg_resources

    # Load up the additional entry point defined backends
    for entry_point in pkg_resources.iter_entry_points('beaker.backends'):
        try:
            NamespaceManager = entry_point.load()
            name = entry_point.name
            if name in clsmap:
                raise BeakerException("NamespaceManager name conflict,'%s' "
                                      "already loaded" % name)
            clsmap[name] = NamespaceManager
        except (InvalidCacheBackendError, SyntaxError):
            # Ignore invalid backends
            pass
        except:
            import sys
            from pkg_resources import DistributionNotFound
            # Warn when there's a problem loading a NamespaceManager
            if not isinstance(sys.exc_info()[1], DistributionNotFound):
                import traceback
                from StringIO import StringIO
                tb = StringIO()
                traceback.print_exc(file=tb)
                warnings.warn(
                    "Unable to load NamespaceManager entry point: '%s': "