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


Python PersistentMapping.has_key方法代码示例

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


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

示例1: PSession

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import has_key [as 别名]
class PSession( base.Session, Persistent ):
    """
    Keys which are already used in the data dictionary of each session:
        - menuStatus: it is used for knowing if the conference display menu is closed or opened.
        - accessKeys: contains all the access keys entered by the user in this session
        - modifKeys: contains all the modification keys entered by the user in this session
    """

    def __init__(self, request, id):
        base.Session.__init__(self, request, id)
        self.user = None
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        self.datadict = PersistentMapping()
        base.Session.__init__(self, request, id)
        self._lang = minfo.getLang()
        self.datadict["ActiveTimezone"] = "LOCAL"

    @property
    def csrf_token(self):
        try:
            return self._csrf_token
        except AttributeError:
            self._csrf_token = str(uuid.uuid4())
            return self._csrf_token

    def reset_csrf_token(self):
        if hasattr(self, '_csrf_token'):
            del self._csrf_token

    @property
    def csrf_protected(self):
        """Does the session need CSRF protection?"""
        return self.user is not None

    def has_info (self):
        """has_info() -> boolean

        Return true if this session contains any information that must
        be saved.
        """
        # This flag will indicate when to commit a session
        return getattr(self, '_v_modified', False)

    def setUser( self, newUser ):
        if newUser:
            self._lang = newUser.getLang()
        self.user = newUser
        self._v_modified = True

    def getUser( self ):
        return self.user

    def getId( self ):
        return self.id

    def setVar(self, key, value):
        try:
            self.datadict[key] = value
        except AttributeError:
            self.datadict = PersistentMapping()
            self.datadict[key] = value
        self._v_modified = True

    def getVar(self, key):
        try:
            if self.datadict:
                pass
        except AttributeError:
            self.datadict = PersistentMapping()
            return None
        return self.datadict.get(key,None)

    def removeVar(self, key):
        try:
            if self.datadict:
                pass
        except AttributeError:
            self.datadict = PersistentMapping()
            return None
        if self.datadict.has_key(key):
            del self.datadict[key]
            self._v_modified = True

    def getLang(self):
        try:
            if self._lang is None:
                raise Exception("no language")
        except:
            try:
                lang=self.user.getLang()
            except:
                lang="en_GB"
                Logger.get('i18n').debug('No user language defined. Using %s as default.' % lang)
            self._lang = lang

        return self._lang

    def setLang(self, lang):
        self._lang = lang
        self._v_modified = True
#.........这里部分代码省略.........
开发者ID:iason-andr,项目名称:indico,代码行数:103,代码来源:sessionManagement.py

示例2: TinyTablePlus

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import has_key [as 别名]

#.........这里部分代码省略.........

        for i in range(0, self.n_cols):
            # Modified by SDH for key_cols.
            name = self._col_names[i] + TypeNames[self._types[i]]
            if hasattr(self, '_key_cols') and name in self._key_cols:
                name = name + '*'
            l.append(name)

        return string.join(l, ' ')
        
    def data_text(self):
        return ImportExport.ExportData(self._rows)

    def index_html(self):
        """Returns an HTML representation of the TinyTablePlus's data"""

        s = "<table border=1><tr><th>"
        s = s + string.join(self._col_names, "</th>\n<th>") + "</th></tr>\n"
        for row in self._rows:
            s = s + "<tr><td>" + \
                string.join(map(str, row), "</td>\n<td>") + "</td></tr>\n"
        return s + "</table>"

    def _results(self, rows):
        if hasattr(self, '_v_brain'):
            brain = self._v_brain
        else:
            brain = self._v_brain = getBrain(self.class_file_, self.class_name_)
        return Results((self._items, rows), brains=brain, parent=None)

    def __call__(self, *args, **kargs):
        # print self.id, args, kargs.keys()
        if len(args) == 1:
            if self._index.has_key(args[0]):
                return self._results([self._rows[self._index[args[0]]]])
            else:
                return None
        elif len(kargs):
            rf = RowFilter(self, kargs)
            l = []

            for i in range(0, len(self._rows)):
                if rf(self._rows[i]):
                    l.append(self._rows[i])
            return self._results(l)
        else:
            return self._results(self._rows)

    # Convenience method added by Shane.
    getRows = __call__

    # The added methods by Shane Hathaway permit programatic
    # changes of the table contents.
    def delRows(self, *args, **kargs):
        '''Returns the number of rows deleted.
        '''
        if len(args) == 1:
            if self._index.has_key(args[0]):
                i = self._index[args[0]]
                if i >= 0:
                    del self._rows[i]
                    self._GenerateIndex()
                    return 1
            else:
                return 0
        elif len(kargs):
开发者ID:eaudeweb,项目名称:EionetProducts,代码行数:70,代码来源:TinyTablePlus.py

示例3: BaseQuestion

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import has_key [as 别名]
class BaseQuestion(BaseContent):
    """Base class for survey questions"""
    immediate_view = "base_edit"
    global_allow = 0
    filter_content_types = 1
    allowed_content_types = ()
    include_default_actions = 1
    _at_rename_after_creation = True

    def __init__(self, oid, **kwargs):
        self.reset()
        BaseContent.__init__(self, oid, **kwargs)

    security = ClassSecurityInfo()

    security.declareProtected(CMFCorePermissions.View, 'getAbstract')
    def getAbstract(self, **kw):
        return self.Description()

    security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'setAbstract')
    def setAbstract(self, val, **kw):
        self.setDescription(val)

    security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'reset')
    def reset(self):
        """Remove answers for all users."""
        if USE_BTREE:
            self.answers = OOBTree()
        else:
            self.answers = PersistentMapping()

    security.declareProtected(CMFCorePermissions.ModifyPortalContent, 'resetForUser')
    def resetForUser(self, userid):
        """Remove answer for a single user"""
        if self.answers.has_key(userid):
            del self.answers[userid]

    security.declareProtected(CMFCorePermissions.View, 'addAnswer')
    def addAnswer(self, value, comments=""):
        """Add an answer and optional comments for a user.
        This method protects _addAnswer from anonymous users specifying a
        userid when they vote, and thus apparently voting as another user
        of their choice.
        """
        # Get hold of the parent survey
        survey = None
        ob = self
        while survey is None:
            ob = ob.aq_parent
            if ob.meta_type == 'Survey':
                survey = ob
            elif getattr(ob, '_isPortalRoot', False):
                raise Exception("Could not find a parent Survey.")
        portal_membership = getToolByName(self, 'portal_membership')
        if portal_membership.isAnonymousUser() and not survey.getAllowAnonymous():
            raise Unauthorized, ("This survey is not available to anonymous users.")
        # Use the survey to get hold of the appropriate userid
        userid = survey.getSurveyId()
        # Call the real method for storing the answer for this user.
        return self._addAnswer(userid, value, comments)

    def _addAnswer(self, userid, value, comments=""):
        """Add an answer and optional comments for a user."""
        # We don't let users over-write answers that they've already made.
        # Their first answer must be explicitly 'reset' before another
        # answer can be supplied.
        # XXX this causes problem when survey fails validation
        # will also cause problem with save function
##        if self.answers.has_key(userid):
##            # XXX Should this get raised?  If so, a more appropriate
##            # exception is probably in order.
##            msg = "User '%s' has already answered this question. Reset the original response to supply a new answer."
##            raise Exception(msg % userid)
##        else:
        self.answers[userid] = PersistentMapping(value=value,
                                                 comments=comments)
        if not isinstance(self.answers, (PersistentMapping, OOBTree)):
            # It must be a standard dictionary from an old install, so
            # we need to inform the ZODB about the change manually.
            self.answers._p_changed = 1

    security.declareProtected(CMFCorePermissions.View, 'getAnswerFor')
    def getAnswerFor(self, userid):
        """Get a specific user's answer"""
        answer = self.answers.get(userid, {}).get('value', None)
        if self.getInputType() in ['multipleSelect', 'checkbox']:
            if type(answer) == 'NoneType':
                return []
        return answer

    security.declareProtected(CMFCorePermissions.View, 'getCommentsFor')
    def getCommentsFor(self, userid):
        """Get a specific user's comments"""
        return self.answers.get(userid, {}).get('comments', None)

    security.declareProtected(CMFCorePermissions.View, 'getComments')
    def getComments(self):
        """Return a userid, comments mapping"""
        mlist = []
        for k, v in self.answers.items():
#.........这里部分代码省略.........
开发者ID:cislgov,项目名称:cisl.portal.plone25,代码行数:103,代码来源:BaseQuestion.py

示例4: address

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import has_key [as 别名]
class HasEmail:
    """Mixin class proving email address(es) and related functions"""
    
    def __init__(self):
        self.__items = []
        self.__unconfirmed = PersistentMapping()
        self.primary_email = None
        
    def is_valid_email(cls, email):
        """Class method returns True if email is valid, or False if it should
        be rejected.

        >>> HasEmail.is_valid_email('[email protected]')
        True
        >>> HasEmail.is_valid_email('[email protected]')
        True
        >>> HasEmail.is_valid_email('[email protected]')
        True
        >>> HasEmail.is_valid_email('xyz')
        False
        >>> HasEmail.is_valid_email('[email protected]@foo')
        False
        """
        global _blocked_domains
        
        if email.find('@') == -1:
            return False
        
        if email.count('@') != 1:
            return False
            
        (username, host) = email.split('@')
        if host in _blocked_domains:
            return False
        
        return True
        
    is_valid_email = classmethod(is_valid_email)
        
    def add_email(self, email):
        """Add email to the list. Adds primary if none set."""
        email = email.lower()
        if email not in self.__items:
            self.__items.append(email)
            self._p_changed = 1

        if self.primary_email is None:
            self.primary_email = email
            
    def add_unconfirmed_email(self, email):
        """Add new e-mail that has not yet been confirmed. Call confirm_email to move
        into active list of e-mails.
        Returns confirmation code that must be given to confirm_email to confirm.
        """
        email = email.lower()
        if not self.__unconfirmed.has_key(email):
            self.__unconfirmed[email] = _password_generator.generate(seed=email)
        return self.__unconfirmed[email]
        
    def remove_unconfirmed_email(self, email):
        email = email.lower()
        if self.__unconfirmed.has_key(email):
            del self.__unconfirmed[email]
            
    def confirm_email(self, code):
        """Confirm email with the given code, or return False if invalid code."""
        for email, conf_code in self.__unconfirmed.items():
            if conf_code == code:
                self.add_email(email)
                del self.__unconfirmed[email]
                self.notify_email_confirmed(email)
                return email
        return None
    
    def remove_email(self, email):
        """Remove an e-mail address from the list. Raises KeyError if only one e-mail address left"""
        email = email.lower()
        if self.__unconfirmed.has_key(email):
            return self.remove_unconfirmed_email(email)
            
        emails = self.email_list()
        if len(emails) > 1:
            self.__items.remove(email)
            self._p_changed = 1
            if email == self.get_primary_email():
                self.set_primary_email(self.email_list()[0])
        else:
            raise KeyError
            
    def remove_all_emails(self):
        self.__items = []
        self.primary_email = None
        
    def has_email(self, email):
        email = email.lower()
        return email in self.__items

    def email_list(self):
        return self.__items
        
#.........这里部分代码省略.........
开发者ID:mrmaple,项目名称:open_qon,代码行数:103,代码来源:user.py

示例5: PSession

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import has_key [as 别名]
class PSession( base.Session, Persistent ):
    """
    Keys which are already used in the data dictionary of each session: 
        - currentCategoryId: it is used for knowing which is the category that contains the current conference.
        - menuStatus: it is used for knowing if the conference display menu is closed or opened.
        - accessKeys: contains all the access keys entered by the user in this session
        - modifKeys: contains all the modification keys entered by the user in this session
    """
    
    def __init__(self, request, id):
        base.Session.__init__(self, request, id)
        self.user = None
        minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        self.datadict = PersistentMapping() 
        base.Session.__init__(self, request, id) 
        #minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
        #self.setVar("ActiveTimezone",minfo.getTimezone())
        self._lang = minfo.getLang()        
        self.setVar("ActiveTimezone","LOCAL")

    def setUser( self, newUser ):
        if newUser:
            self._lang = newUser.getLang()
        self.user = newUser
        #get_transaction().commit()

    def getUser( self ):
        return self.user

    def getId( self ):
        return self.id
        
    def setVar(self, key, value):
        try:
            self.datadict[key] = value
        except AttributeError:
            self.datadict = PersistentMapping()
            self.datadict[key] = value
            
    def getVar(self, key):
        try:
            if self.datadict:
                pass
        except AttributeError:
            self.datadict = PersistentMapping()
            return None
        return self.datadict.get(key,None)

    def removeVar(self, key):
        try:
            if self.datadict:
                pass
        except AttributeError:
            self.datadict = PersistentMapping()
            return None
        if self.datadict.has_key(key):
            del self.datadict[key]

    def getLang(self):
        try:
            if self._lang is None:
                raise Exception("no language")
        except:
            try:                
                lang=self.user.getLang()                
            except:
                lang="en_US"
                Logger.get('i18n').debug('No user language defined. Using %s as default.' % lang)
            self._lang = lang
            
        return self._lang
         
    def setLang(self, lang):
        self._lang = lang
开发者ID:lukasnellen,项目名称:indico,代码行数:76,代码来源:sessionManagement.py


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