当前位置: 首页>>代码示例>>Python>>正文


Python GenericCache.get方法代码示例

本文整理汇总了Python中MaKaC.common.cache.GenericCache.get方法的典型用法代码示例。如果您正苦于以下问题:Python GenericCache.get方法的具体用法?Python GenericCache.get怎么用?Python GenericCache.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在MaKaC.common.cache.GenericCache的用法示例。


在下文中一共展示了GenericCache.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: principal_from_fossil

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
def principal_from_fossil(fossil, allow_pending=False, allow_groups=True, legacy=True, allow_missing_groups=False,
                          allow_emails=False, allow_networks=False):
    from indico.modules.networks.models.networks import IPNetworkGroup
    from indico.modules.groups import GroupProxy
    from indico.modules.users import User

    type_ = fossil['_type']
    id_ = fossil['id']
    if type_ == 'Avatar':
        if isinstance(id_, int) or id_.isdigit():
            # regular user
            user = User.get(int(id_))
        elif allow_pending:
            data = GenericCache('pending_identities').get(id_)
            if not data:
                raise ValueError("Cannot find user '{}' in cache".format(id_))

            data = {k: '' if v is None else v for (k, v) in data.items()}
            email = data['email'].lower()

            # check if there is not already a (pending) user with that e-mail
            # we need to check for non-pending users too since the search may
            # show a user from external results even though the email belongs
            # to an indico account in case some of the search criteria did not
            # match the indico account
            user = User.find_first(User.all_emails.contains(email), ~User.is_deleted)
            if not user:
                user = User(first_name=data.get('first_name') or '', last_name=data.get('last_name') or '',
                            email=email,
                            address=data.get('address', ''), phone=data.get('phone', ''),
                            affiliation=data.get('affiliation', ''), is_pending=True)
                db.session.add(user)
                db.session.flush()
        else:
            raise ValueError("Id '{}' is not a number and allow_pending=False".format(id_))
        if user is None:
            raise ValueError('User does not exist: {}'.format(id_))
        return user.as_avatar if legacy else user
    elif allow_emails and type_ == 'Email':
        return EmailPrincipal(id_)
    elif allow_networks and type_ == 'IPNetworkGroup':
        group = IPNetworkGroup.get(int(id_))
        if group is None:
            raise ValueError('IP network group does not exist: {}'.format(id_))
        return group
    elif allow_groups and type_ in {'LocalGroupWrapper', 'LocalGroup'}:
        group = GroupProxy(int(id_))
        if group.group is None:
            raise ValueError('Local group does not exist: {}'.format(id_))
        return group.as_legacy_group if legacy else group
    elif allow_groups and type_ in {'LDAPGroupWrapper', 'MultipassGroup'}:
        provider = fossil['provider']
        group = GroupProxy(id_, provider)
        if group.group is None and not allow_missing_groups:
            raise ValueError('Multipass group does not exist: {}:{}'.format(provider, id_))
        return group.as_legacy_group if legacy else group
    else:
        raise ValueError('Unexpected fossil type: {}'.format(type_))
开发者ID:fph,项目名称:indico,代码行数:60,代码来源:user.py

示例2: principal_from_fossil

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
def principal_from_fossil(fossil, allow_pending=False, allow_groups=True, legacy=True, allow_missing_groups=False,
                          allow_emails=False):
    """Gets a GroupWrapper or AvatarUserWrapper from a fossil"""
    from indico.modules.groups import GroupProxy
    from indico.modules.users import User

    type_ = fossil['_type']
    id_ = fossil['id']
    if type_ == 'Avatar':
        if isinstance(id_, int) or id_.isdigit():
            # regular user
            user = User.get(int(id_))
        elif allow_pending:
            data = GenericCache('pending_identities').get(id_)
            if not data:
                raise ValueError("Cannot find user '{}' in cache".format(id_))

            data = {k: '' if v is None else v for (k, v) in data.items()}
            email = data['email'].lower()

            # check if there is not already a pending user with that e-mail
            user = User.find_first(email=email, is_pending=True)
            if not user:
                user = User(first_name=data.get('first_name') or '', last_name=data.get('last_name') or '',
                            email=email,
                            address=data.get('address', ''), phone=data.get('phone', ''),
                            affiliation=data.get('affiliation', ''), is_pending=True)
                db.session.add(user)
                db.session.flush()
        else:
            raise ValueError("Id '{}' is not a number and allow_pending=False".format(id_))
        if user is None:
            raise ValueError('User does not exist: {}'.format(id_))
        return user.as_avatar if legacy else user
    elif allow_emails and type_ == 'Email':
        return EmailPrincipal(id_)
    elif allow_groups and type_ in {'LocalGroupWrapper', 'LocalGroup'}:
        group = GroupProxy(int(id_))
        if group.group is None:
            raise ValueError('Local group does not exist: {}'.format(id_))
        return group.as_legacy_group if legacy else group
    elif allow_groups and type_ in {'LDAPGroupWrapper', 'MultipassGroup'}:
        provider = fossil['provider']
        group = GroupProxy(id_, provider)
        if group.group is None and not allow_missing_groups:
            raise ValueError('Multipass group does not exist: {}:{}'.format(provider, id_))
        return group.as_legacy_group if legacy else group
    else:
        raise ValueError('Unexpected fossil type: {}'.format(type_))
开发者ID:MichelCordeiro,项目名称:indico,代码行数:51,代码来源:user.py

示例3: SudsCache

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
class SudsCache(Cache):
    _instance = None

    def __init__(self, duration=DEFAULT_CACHE_TTL):
        self._cache = GenericCache("SudsCache")
        self._duration = duration

    def get(self, key):
        self._cache.get(key)

    def put(self, key, val):
        self._cache.set(key, val, self._duration)

    def purge(self, key):
        self._cache.delete(key)
开发者ID:florv,项目名称:indico-plugins,代码行数:17,代码来源:cache.py

示例4: RHRoomBookingMapOfRoomsWidget

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
class RHRoomBookingMapOfRoomsWidget(RHRoomBookingBase):
    def __init__(self, *args, **kwargs):
        RHRoomBookingBase.__init__(self, *args, **kwargs)
        self._cache = GenericCache('MapOfRooms')

    def _checkParams(self):
        RHRoomBookingBase._checkParams(self, request.args)
        self._room_id = request.args.get('roomID')

    def _process(self):
        key = str(sorted(dict(request.args, lang=session.lang, user=session.user.getId()).items()))
        html = self._cache.get(key)
        if not html:
            default_location = Location.default_location
            aspects = [a.to_serializable() for a in default_location.aspects]
            buildings = default_location.get_buildings()
            html = WPRoomBookingMapOfRoomsWidget(self,
                                                 aspects=aspects,
                                                 buildings=buildings,
                                                 room_id=self._room_id,
                                                 default_repeat='{}|0'.format(RepeatFrequency.NEVER),
                                                 default_start_dt=datetime.combine(date.today(),
                                                                                   Location.working_time_start),
                                                 default_end_dt=datetime.combine(date.today(),
                                                                                 Location.working_time_end),
                                                 repeat_mapping=RepeatMapping.getMapping()).display()
            self._cache.set(key, html, 3600)
        return html
开发者ID:sofian86,项目名称:indico-gh-test,代码行数:30,代码来源:rooms.py

示例5: _send_confirmation

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
 def _send_confirmation(self, email):
     token_storage = GenericCache('confirm-email')
     data = {'email': email, 'user_id': self.user.id}
     token = make_unique_token(lambda t: not token_storage.get(t))
     token_storage.set(token, data, 24 * 3600)
     GenericMailer.send(make_email(email, template=get_template_module('users/emails/verify_email.txt',
                                                                       user=self.user, email=email, token=token)))
开发者ID:fph,项目名称:indico,代码行数:9,代码来源:controllers.py

示例6: wrapper

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
 def wrapper(*args, **kwargs):
     cache = GenericCache('task-locks')
     name = current_task.name
     if cache.get(name):
         Logger.get('celery').warning('Task {} is locked; not executing it'.format(name))
         return
     cache.set(name, True)
     try:
         return f(*args, **kwargs)
     finally:
         cache.delete(name)
开发者ID:dbourillot,项目名称:indico,代码行数:13,代码来源:util.py

示例7: send_login_info

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
def send_login_info(user, event=None):
    token_storage = GenericCache('resetpass')
    endpoint = 'event.confLogin-resetPassword' if event else 'user.signIn-resetPassword'

    idList = user.getIdentityList()
    logins = []
    for id in idList:
        if not hasattr(id, 'setPassword'):
            config = Config.getInstance()
            extra_message = config.getAuthenticatorConfigById(id.getAuthenticatorTag()).get("ResetPasswordMessage")
            msg = _("Sorry, you are using an externally managed account (%s) to login into Indico.") % id.getLogin()
            if extra_message:
                msg += "\n" + extra_message
            logins.append({
                'tag': id.getAuthenticatorTag(),
                'login': id.getLogin(),
                'error': msg
            })
        else:
            tag = id.getAuthenticatorTag()
            login = id.getLogin()
            data = {'tag': tag, 'login': login}
            token = str(uuid.uuid4())
            while token_storage.get(token):
                token = str(uuid.uuid4())
            token_storage.set(token, data, 6*3600)
            url = url_for(endpoint, event, token=token, _external=True, _secure=True)
            logins.append({
                'tag': tag,
                'login': login,
                'link': url
            })
    if not logins:
        url = urlHandlers.UHUserDetails.getURL(user)
        text = _("Sorry, we did not find your login.\nPlease, create one here:\n%s") % url
    else:
        text = _("You can use the following links within the next six hours to reset your password.")
        for entry in logins:
            text += "\n\n==================\n"
            if 'link' in entry:
                text += _("Click below to reset your password for the %s login '%s':\n") % (entry['tag'],
                                                                                            entry['login'])
                text += entry['link']
            else:
                text += entry['error']
            text += "\n==================\n"
    maildata = {
        "fromAddr": "Indico Mailer <%s>" % Config.getInstance().getNoReplyEmail(),
        "toList": [user.getEmail()],
        "subject": _("[%s] Login Information") % getSubjectIndicoTitle(),
        "body": text
    }
    GenericMailer.send(GenericNotification(maildata))
开发者ID:Ictp,项目名称:indico,代码行数:55,代码来源:mail.py

示例8: _get_user_data

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
 def _get_user_data(self):
     user_id = request.args.get('user')
     if user_id is None:
         return {}
     elif user_id.isdigit():
         # existing indico user
         user = User.find_first(id=user_id, is_deleted=False)
         return {t.name: getattr(user, t.name, None) if user else '' for t in PersonalDataType}
     else:
         # non-indico user
         data = GenericCache('pending_identities').get(user_id, {})
         return {t.name: data.get(t.name) for t in PersonalDataType}
开发者ID:irek-zaripov,项目名称:indico,代码行数:14,代码来源:reglists.py

示例9: has_member

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
 def has_member(self, user):
     cache = GenericCache('group-membership')
     key = '{}:{}:{}'.format(self.provider, self.name, user.id)
     rv = cache.get(key)
     if rv is not None:
         return rv
     elif self.group is None:
         warn('Tried to check if {} is in invalid group {}'.format(user, self))
         rv = False
     else:
         rv = any(x[1] in self.group for x in user.iter_identifiers(check_providers=True, providers={self.provider}))
     cache.set(key, rv, 1800)
     return rv
开发者ID:marcosmolla,项目名称:indico,代码行数:15,代码来源:core.py

示例10: _get_user_data

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
 def _get_user_data(self):
     user_id = request.args.get("user")
     if user_id is None:
         return {}
     elif user_id.isdigit():
         # existing indico user
         user = User.find_first(id=user_id, is_deleted=False)
         user_data = {t.name: getattr(user, t.name, None) if user else "" for t in PersonalDataType}
     else:
         # non-indico user
         data = GenericCache("pending_identities").get(user_id, {})
         user_data = {t.name: data.get(t.name) for t in PersonalDataType}
     user_data["title"] = get_title_uuid(self.regform, user_data["title"])
     return user_data
开发者ID:florv,项目名称:indico,代码行数:16,代码来源:reglists.py

示例11: SudsCache

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
class SudsCache(Cache):
    _instance = None

    @classmethod
    def getInstance(cls, duration=None):
        if cls._instance is None:
            cls._instance = SudsCache(duration)
        return cls._instance

    def __init__(self, duration=None):
        self._cache = GenericCache("SudsCache")
        if duration is None:
            duration = 24 * 3600 # we put as default 1 day cache
        self._duration = duration

    def get(self, key):
        self._cache.get(key)

    def put(self, key, val):
        self._cache.set(key, val, self._duration)

    def purge(self, key):
        self._cache.delete(key)
开发者ID:Ictp,项目名称:indico,代码行数:25,代码来源:cache.py

示例12: get

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
    def get(cls, *args, **kwargs):
        """Create and return a serializable Report object, retrieved from cache if possible"""

        from indico_piwik.plugin import PiwikPlugin

        if not PiwikPlugin.settings.get('cache_enabled'):
            return cls(*args, **kwargs).to_serializable()

        cache = GenericCache('Piwik.Report')
        key = u'{}-{}-{}'.format(cls.__name__, args, kwargs)

        report = cache.get(key)
        if not report:
            report = cls(*args, **kwargs)
            cache.set(key, report, PiwikPlugin.settings.get('cache_ttl'))
        return report.to_serializable()
开发者ID:florv,项目名称:indico-plugins,代码行数:18,代码来源:reports.py

示例13: CachedReport

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
class CachedReport(object):
    """
    This class acts as a wrapper for functions which return a report object,
    by decorating the get<report> methods with the memonize function in the
    BaseStatisticsReport object, the result is wrapped here and its age
    is compared with the TTL if in the cache, either returning said item or
    allowing the method to generate a new one.
    """

    _config = StatisticsConfig()

    def __init__(self, function):
        self._function = function

        # Cache bucket per implementation
        plugin = function.__module__.split('.')[3]
        self._cache = GenericCache(plugin + 'StatisticsCache')

    def getReport(self, *args, **kwargs):
        """
        Ascertain if live updating first, if so disregard and continue.
        """

        ttl = self._config.getUpdateInterval()

        if not self._config.hasCacheEnabled():
            return self._function(*args, **kwargs)

        keyParams = list(args)
        keyParams.extend([self._function.__module__, self._function.__name__])
        key = self._generateKey(keyParams)

        resource = self._cache.get(key, None)

        if not resource:
            result = self._function(*args, **kwargs)
            self._cache.set(key, result, ttl)
            return result
        else:
            return resource

    def _generateKey(self, params):
        """
        Generates a unique key for caching against the params given.
        """
        return reduce(lambda x, y: str(x) + '-' + str(y), params)
开发者ID:arturodr,项目名称:indico,代码行数:48,代码来源:implementation.py

示例14: handler

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
def handler(req, **params):
    ContextManager.destroy()
    logger = Logger.get('httpapi')
    path, query = req.URLFields['PATH_INFO'], req.URLFields['QUERY_STRING']
    if req.method == 'POST':
        # Convert POST data to a query string
        queryParams = dict(req.form)
        for key, value in queryParams.iteritems():
            queryParams[key] = [str(value)]
        query = urllib.urlencode(remove_lists(queryParams))
    else:
        # Parse the actual query string
        queryParams = parse_qs(query)

    dbi = DBMgr.getInstance()
    dbi.startRequest()
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    if minfo.getRoomBookingModuleActive():
        Factory.getDALManager().connect()

    apiKey = get_query_parameter(queryParams, ['ak', 'apikey'], None)
    cookieAuth = get_query_parameter(queryParams, ['ca', 'cookieauth'], 'no') == 'yes'
    signature = get_query_parameter(queryParams, ['signature'])
    timestamp = get_query_parameter(queryParams, ['timestamp'], 0, integer=True)
    noCache = get_query_parameter(queryParams, ['nc', 'nocache'], 'no') == 'yes'
    pretty = get_query_parameter(queryParams, ['p', 'pretty'], 'no') == 'yes'
    onlyPublic = get_query_parameter(queryParams, ['op', 'onlypublic'], 'no') == 'yes'
    onlyAuthed = get_query_parameter(queryParams, ['oa', 'onlyauthed'], 'no') == 'yes'

    # Get our handler function and its argument and response type
    hook, dformat = HTTPAPIHook.parseRequest(path, queryParams)
    if hook is None or dformat is None:
        raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

    # Disable caching if we are not just retrieving data (or the hook requires it)
    if req.method == 'POST' or hook.NO_CACHE:
        noCache = True

    ak = error = result = None
    ts = int(time.time())
    typeMap = {}
    try:
        session = None
        if cookieAuth:
            session = getSessionForReq(req)
            if not session.getUser():  # ignore guest sessions
                session = None

        if apiKey or not session:
            # Validate the API key (and its signature)
            ak, enforceOnlyPublic = checkAK(apiKey, signature, timestamp, path, query)
            if enforceOnlyPublic:
                onlyPublic = True
            # Create an access wrapper for the API key's user
            aw = buildAW(ak, req, onlyPublic)
            # Get rid of API key in cache key if we did not impersonate a user
            if ak and aw.getUser() is None:
                cacheKey = normalizeQuery(path, query,
                                          remove=('ak', 'apiKey', 'signature', 'timestamp', 'nc', 'nocache',
                                                  'oa', 'onlyauthed'))
            else:
                cacheKey = normalizeQuery(path, query,
                                          remove=('signature', 'timestamp', 'nc', 'nocache', 'oa', 'onlyauthed'))
                if signature:
                    # in case the request was signed, store the result under a different key
                    cacheKey = 'signed_' + cacheKey
        else:
            # We authenticated using a session cookie.
            if Config.getInstance().getCSRFLevel() >= 2:
                token = req.headers_in.get('X-CSRF-Token', get_query_parameter(queryParams, ['csrftoken']))
                if session.csrf_token != token:
                    raise HTTPAPIError('Invalid CSRF token', apache.HTTP_FORBIDDEN)
            aw = AccessWrapper()
            if not onlyPublic:
                aw.setUser(session.getUser())
            userPrefix = 'user-' + session.getUser().getId() + '_'
            cacheKey = userPrefix + normalizeQuery(path, query,
                                                   remove=('nc', 'nocache', 'ca', 'cookieauth', 'oa', 'onlyauthed',
                                                           'csrftoken'))

        # Bail out if the user requires authentication but is not authenticated
        if onlyAuthed and not aw.getUser():
            raise HTTPAPIError('Not authenticated', apache.HTTP_FORBIDDEN)

        obj = None
        addToCache = not hook.NO_CACHE
        cache = GenericCache('HTTPAPI')
        cacheKey = RE_REMOVE_EXTENSION.sub('', cacheKey)
        if not noCache:
            obj = cache.get(cacheKey)
            if obj is not None:
                result, extra, ts, complete, typeMap = obj
                addToCache = False
        if result is None:
            # Perform the actual exporting
            res = hook(aw, req)
            if isinstance(res, tuple) and len(res) == 4:
                result, extra, complete, typeMap = res
            else:
                result, extra, complete, typeMap = res, {}, True, {}
#.........这里部分代码省略.........
开发者ID:jt1,项目名称:indico,代码行数:103,代码来源:handlers.py

示例15: handler

# 需要导入模块: from MaKaC.common.cache import GenericCache [as 别名]
# 或者: from MaKaC.common.cache.GenericCache import get [as 别名]
def handler(prefix, path):
    path = posixpath.join('/', prefix, path)
    ContextManager.destroy()
    clearCache()  # init fossil cache
    logger = Logger.get('httpapi')
    if request.method == 'POST':
        # Convert POST data to a query string
        queryParams = dict((key, value.encode('utf-8')) for key, value in request.form.iteritems())
        query = urllib.urlencode(queryParams)
    else:
        # Parse the actual query string
        queryParams = dict((key, value.encode('utf-8')) for key, value in request.args.iteritems())
        query = request.query_string

    dbi = DBMgr.getInstance()
    dbi.startRequest()
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    if minfo.getRoomBookingModuleActive():
        Factory.getDALManager().connect()

    apiKey = get_query_parameter(queryParams, ['ak', 'apikey'], None)
    cookieAuth = get_query_parameter(queryParams, ['ca', 'cookieauth'], 'no') == 'yes'
    signature = get_query_parameter(queryParams, ['signature'])
    timestamp = get_query_parameter(queryParams, ['timestamp'], 0, integer=True)
    noCache = get_query_parameter(queryParams, ['nc', 'nocache'], 'no') == 'yes'
    pretty = get_query_parameter(queryParams, ['p', 'pretty'], 'no') == 'yes'
    onlyPublic = get_query_parameter(queryParams, ['op', 'onlypublic'], 'no') == 'yes'
    onlyAuthed = get_query_parameter(queryParams, ['oa', 'onlyauthed'], 'no') == 'yes'
    oauthToken = 'oauth_token' in queryParams

    # Get our handler function and its argument and response type
    hook, dformat = HTTPAPIHook.parseRequest(path, queryParams)
    if hook is None or dformat is None:
        raise NotFound

    # Disable caching if we are not just retrieving data (or the hook requires it)
    if request.method == 'POST' or hook.NO_CACHE:
        noCache = True

    ak = error = result = None
    ts = int(time.time())
    typeMap = {}
    responseUtil = ResponseUtil()
    try:
        used_session = None
        if cookieAuth:
            used_session = session
            if not used_session.user:  # ignore guest sessions
                used_session = None

        if apiKey or oauthToken or not used_session:
            if not oauthToken:
                # Validate the API key (and its signature)
                ak, enforceOnlyPublic = checkAK(apiKey, signature, timestamp, path, query)
                if enforceOnlyPublic:
                    onlyPublic = True
                # Create an access wrapper for the API key's user
                aw = buildAW(ak, onlyPublic)
            else: # Access Token (OAuth)
                at = OAuthUtils.OAuthCheckAccessResource()
                aw = buildAW(at, onlyPublic)
            # Get rid of API key in cache key if we did not impersonate a user
            if ak and aw.getUser() is None:
                cacheKey = normalizeQuery(path, query,
                                          remove=('_', 'ak', 'apiKey', 'signature', 'timestamp', 'nc', 'nocache',
                                                  'oa', 'onlyauthed'))
            else:
                cacheKey = normalizeQuery(path, query,
                                          remove=('_', 'signature', 'timestamp', 'nc', 'nocache', 'oa', 'onlyauthed'))
                if signature:
                    # in case the request was signed, store the result under a different key
                    cacheKey = 'signed_' + cacheKey
        else:
            # We authenticated using a session cookie.
            if Config.getInstance().getCSRFLevel() >= 2:
                token = request.headers.get('X-CSRF-Token', get_query_parameter(queryParams, ['csrftoken']))
                if used_session.csrf_protected and used_session.csrf_token != token:
                    raise HTTPAPIError('Invalid CSRF token', 403)
            aw = AccessWrapper()
            if not onlyPublic:
                aw.setUser(used_session.user)
            userPrefix = 'user-' + used_session.user.getId() + '_'
            cacheKey = userPrefix + normalizeQuery(path, query,
                                                   remove=('_', 'nc', 'nocache', 'ca', 'cookieauth', 'oa', 'onlyauthed',
                                                           'csrftoken'))

        # Bail out if the user requires authentication but is not authenticated
        if onlyAuthed and not aw.getUser():
            raise HTTPAPIError('Not authenticated', 403)

        addToCache = not hook.NO_CACHE
        cache = GenericCache('HTTPAPI')
        cacheKey = RE_REMOVE_EXTENSION.sub('', cacheKey)
        if not noCache:
            obj = cache.get(cacheKey)
            if obj is not None:
                result, extra, ts, complete, typeMap = obj
                addToCache = False
        if result is None:
            # Perform the actual exporting
#.........这里部分代码省略.........
开发者ID:jbenito3,项目名称:indico,代码行数:103,代码来源:handlers.py


注:本文中的MaKaC.common.cache.GenericCache.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。