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


Python PersistentMapping.get方法代码示例

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


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

示例1: MollieIdealMultiplePayments

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class MollieIdealMultiplePayments(object):
    implements(IMollieIdealMultiplePayments)
    adapts(IAttributeAnnotatable)

    def __init__(self, context):
        self.ideal_wrapper = getUtility(IMollieIdeal)
        annotations = IAnnotations(context)
        self._metadata = annotations.get(
            IDEAL_MULTIPLE_PAYMENTS_ANNOTATION_KEY, None)
        if self._metadata is None:
            self._metadata = PersistentMapping()
            annotations[IDEAL_MULTIPLE_PAYMENTS_ANNOTATION_KEY] = \
                self._metadata

    # Methods

    def get_banks(self):
        return self.ideal_wrapper.get_banks()

    def get_payment_url(self, partner_id, bank_id, amount, message,
                        report_url, return_url, profile_key=None):
        transaction_id, url = self.ideal_wrapper.request_payment(
            partner_id, bank_id, amount, message, report_url,
            return_url, profile_key)

        self._metadata[transaction_id] = {
            'partner_id': partner_id,
            'profile_key': profile_key,
            'amount': amount,
            'last_update': DateTime(),
            'curreny': None,
            'status': None,
            'paid': None,
            'consumer': {},
            'last_status': None,
            }
        return transaction_id, url

    def get_transaction(self, transaction_id):
        transaction = self._metadata.get(transaction_id)
        if transaction is None:
            raise UnknownTransactionError
        return transaction

    def get_payment_status(self, transaction_id):
        transaction = self.get_transaction(transaction_id)
        order_info = self.ideal_wrapper.check_payment(
            transaction['partner_id'], transaction_id)
        if order_info['status'] != 'CheckedBefore':
            # Only store the main info the first time.
            transaction['currency'] = order_info['currency']
            transaction['paid'] = order_info['paid']
            transaction['consumer'] = order_info.get('consumer')
            transaction['status'] = order_info['status']
        transaction['last_status'] = order_info['status']
        transaction['last_update'] = DateTime()
        return transaction['last_status']
开发者ID:collective,项目名称:collective.mollie,代码行数:59,代码来源:adapter.py

示例2: checkBasicOps

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
    def checkBasicOps(self):
        from persistent.mapping import PersistentMapping
        m = PersistentMapping({'x': 1}, a=2, b=3)
        m['name'] = 'bob'
        self.assertEqual(m['name'], "bob")
        self.assertEqual(m.get('name', 42), "bob")
        self.assert_('name' in m)

        try:
            m['fred']
        except KeyError:
            pass
        else:
            self.fail("expected KeyError")
        self.assert_('fred' not in m)
        self.assertEqual(m.get('fred'), None)
        self.assertEqual(m.get('fred', 42), 42)

        keys = m.keys()
        keys.sort()
        self.assertEqual(keys, ['a', 'b', 'name', 'x'])

        values = m.values()
        values.sort()
        self.assertEqual(values, [1, 2, 3, 'bob'])

        items = m.items()
        items.sort()
        self.assertEqual(items,
                         [('a', 2), ('b', 3), ('name', 'bob'), ('x', 1)])

        keys = list(m.iterkeys())
        keys.sort()
        self.assertEqual(keys, ['a', 'b', 'name', 'x'])

        values = list(m.itervalues())
        values.sort()
        self.assertEqual(values, [1, 2, 3, 'bob'])

        items = list(m.iteritems())
        items.sort()
        self.assertEqual(items,
                         [('a', 2), ('b', 3), ('name', 'bob'), ('x', 1)])
开发者ID:Andyvs,项目名称:TrackMonthlyExpenses,代码行数:45,代码来源:testPersistentMapping.py

示例3: checkBasicOps

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
    def checkBasicOps(self):
        from persistent.mapping import PersistentMapping

        m = PersistentMapping({"x": 1}, a=2, b=3)
        m["name"] = "bob"
        self.assertEqual(m["name"], "bob")
        self.assertEqual(m.get("name", 42), "bob")
        self.assert_("name" in m)

        try:
            m["fred"]
        except KeyError:
            pass
        else:
            self.fail("expected KeyError")
        self.assert_("fred" not in m)
        self.assertEqual(m.get("fred"), None)
        self.assertEqual(m.get("fred", 42), 42)

        keys = m.keys()
        keys.sort()
        self.assertEqual(keys, ["a", "b", "name", "x"])

        values = m.values()
        values.sort()
        self.assertEqual(values, [1, 2, 3, "bob"])

        items = m.items()
        items.sort()
        self.assertEqual(items, [("a", 2), ("b", 3), ("name", "bob"), ("x", 1)])

        keys = list(m.iterkeys())
        keys.sort()
        self.assertEqual(keys, ["a", "b", "name", "x"])

        values = list(m.itervalues())
        values.sort()
        self.assertEqual(values, [1, 2, 3, "bob"])

        items = list(m.iteritems())
        items.sort()
        self.assertEqual(items, [("a", 2), ("b", 3), ("name", "bob"), ("x", 1)])
开发者ID:grodniewicz,项目名称:oship,代码行数:44,代码来源:testPersistentMapping.py

示例4: _data

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
 def _data(self):
     """Return dictionary to store data."""
     sheets_data = getattr(self.context, '_sheets', None)
     if sheets_data is None:
         sheets_data = PersistentMapping()
         setattr(self.context, '_sheets', sheets_data)
     data = sheets_data.get(self._data_key, None)
     if data is None:
         data = PersistentMapping()
         sheets_data[self._data_key] = data
     return data
开发者ID:robx,项目名称:adhocracy3.mercator,代码行数:13,代码来源:__init__.py

示例5: Player

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class Player(OOBTree):
    """Player container, which holds details and game sessions for a single
    player

    """
    implements(interfaces.IPlayer)

    def __init__(self, name, details={}):
        super(Player, self).__init__()
        self.name = name
        self.details = PersistentMapping(details.items())

    @property
    def duration(self):
        total = datetime.timedelta(0)
        for session in self.values():
            total += getattr(session, "duration", datetime.timedelta(0))
        return total

    def session(self, games):
        """Create a new Session for today if needed. Always returns a session
        with games shuffled in random order.

        """
        today = str(datetime.datetime.utcnow().date())
        if not today in self:
            all_games = games.items()
            random.shuffle(all_games)
            selected_games = dict(all_games[:8])
            if self.details.get("assisted", False):
                self[today] = Session(selected_games, 0.30)
            else:
                self[today] = Session(selected_games)
        return self[today]

    def get_sessions(self):
        return map(lambda x: self[x], sorted(self.keys()))
开发者ID:datakurre,项目名称:TIEA221_Tyomuistipeli,代码行数:39,代码来源:datatypes.py

示例6: NotificationTool

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

#.........这里部分代码省略.........
                    'label': 'Rules on discussion item creation (users)',
                    'mode': 'w',
                    'type': 'lines'},
                   {'id': 'on_discussion_item_creation_mail_template',
                    'label': 'Rules on discussion item creation (mail template)',
                    'mode': 'w',
                    'type': 'lines'},
                   )

    security = ClassSecurityInfo()
    decPrivate = security.declarePrivate
    decProtected = security.declareProtected
    decPublic = security.declarePublic


    def __init__(self, *args, **kwargs):
        self._uid_to_path = PersistentMapping()
        self._subscriptions = PersistentMapping()


    #################################################################
    ## Notification handlers
    ########################
    decPrivate('onItemCreation')
    def onItemCreation(self, obj):
        """Handler called when an item is created.

        It returns the number of mails which have been sent.

        **Warning:** this handler is not called when a discussion item
        is added. In this case, ``onDiscussionItemCreation()`` is
        called instead.
        """
        if not self.getProperty('item_creation_notification_enabled'):
            return 0
        if self.ignoreNotification(obj):
            return 0

        extra_bindings = getBasicBindings(obj)
        return self._handlerHelper(obj, 'item_creation',
                                   extra_bindings,
                                   extra_bindings,
                                   extra_bindings)


    decPrivate('onItemModification')
    def onItemModification(self, obj):
        """Handler called when an item is modified.

        It returns the number of mails which have been sent.
        """
        if not self.getProperty('item_modification_notification_enabled'):
            return 0
        if self.ignoreNotification(obj):
            return 0

        extra_bindings = getBasicBindings(obj)
        extra_bindings.update({'current': obj,
                               'previous': getPreviousVersion(obj)})
        return self._handlerHelper(obj, 'item_modification',
                                   extra_bindings,
                                   extra_bindings,
                                   extra_bindings)

    decPrivate('onItemRemoval')
    def onItemRemoval(self, obj):
开发者ID:izak,项目名称:Products.CMFNotification,代码行数:70,代码来源:NotificationTool.py

示例7: Profile

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class Profile(Folder):

    implements(IProfile)

    alert_attachments = 'link'
    fax = '' # BBB
    _websites = ()
    last_login_time = None # BBB

    def _get_website(self):
        old_ws = self.__dict__.get('website')
        if old_ws is not None:
            return old_ws
        return self._websites and self._websites[0] or ''

    website = property(_get_website,)

    def _get_websites(self):
        self._p_activate()
        if '_websites' in self.__dict__:
            return self._websites
        old_ws = self.__dict__.get('website')
        if old_ws is not None:
            return (old_ws,)
        return ()

    def _set_websites(self, value):
        self._websites = value # coerce / normalize?
        if 'website' in self.__dict__:
            del self.__dict__['website']

    websites = property(_get_websites, _set_websites)

    def __init__(self,
                 firstname = '',
                 lastname = '',
                 email = '',
                 phone = '',
                 extension = '',
                 fax = '',
                 department = '',
                 position = '',
                 organization = '',
                 location = '',
                 country = '',
                 websites = None,
                 languages = '',
                 office='',
                 room_no='',
                 biography='',
                 data=None,
                 home_path=None,
                 preferred_communities = None,
                ):
        super(Profile, self).__init__(data)
        self.firstname = firstname
        self.lastname = lastname
        self.email = email
        self.phone = phone
        self.fax = fax
        self.extension = extension
        self.department = department
        self.position = position
        self.organization = organization
        self.location = location
        if country not in countries.as_dict:
            country = 'XX'
        self.country = country
        if websites is not None:
            self.websites = websites
        self.languages = languages
        self.office = office
        self.room_no = room_no
        self.biography = biography
        self.home_path = home_path
        self._alert_prefs = PersistentMapping()
        self._pending_alerts = PersistentList()
        self.categories = PersistentMapping()
        self.password_reset_key = None
        self.password_reset_time = None
        self.preferred_communities = preferred_communities
        self.last_login_time = None

    @property
    def creator(self):
        return self.__name__

    @property
    def title(self):
        title = [self.firstname.strip(), self.lastname.strip()]
        if getattr(self, 'security_state', None) == 'inactive':
            title += ['(Inactive)',]
        return unicode(' '.join(title))

    def get_alerts_preference(self, community_name):
        return self._alert_prefs.get(community_name,
                                     IProfile.ALERT_IMMEDIATELY)

    def set_alerts_preference(self, community_name, preference):
        if preference not in (
#.........这里部分代码省略.........
开发者ID:Falmarri,项目名称:karl,代码行数:103,代码来源:profile.py

示例8: PSession

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [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

示例9: Profile

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class Profile(Folder):

    implements(IProfile)

    alert_attachments = "link"

    def __init__(
        self,
        firstname="",
        lastname="",
        email="",
        phone="",
        extension="",
        fax="",
        department="",
        position="",
        organization="",
        location="",
        country="",
        websites=None,
        languages="",
        office="",
        room_no="",
        biography="",
        data=None,
        home_path=None,
        preferred_communities=None,
        dob=None,
        gender="",
    ):
        super(Profile, self).__init__(data)
        self.firstname = firstname
        self.lastname = lastname
        self.email = email
        self.phone = phone
        self.fax = fax
        self.extension = extension
        self.department = department
        self.position = position
        self.organization = organization
        self.location = location
        if country not in countries.as_dict:
            country = "XX"
        self.country = country
        self.websites = websites or ()
        self.languages = languages
        self.office = office
        self.room_no = room_no
        self.biography = biography
        self.home_path = home_path
        self._alert_prefs = PersistentMapping()
        self._pending_alerts = PersistentList()
        self.categories = PersistentMapping()
        self.password_reset_key = None
        self.password_reset_time = None
        self.preferred_communities = preferred_communities
        self.last_login_time = None
        # states are
        # 1. inactive - user has become inactive rather than deleted from the system.
        # 2. active   - registered with a invite email which creates the profile
        self.security_state = "active"
        self.dob = dob
        self.gender = gender

    @property
    def creator(self):
        return self.__name__

    @property
    def title(self):
        title = [self.firstname.strip(), self.lastname.strip()]
        if getattr(self, "security_state", None) == "inactive":
            title += ["(Inactive)"]
        return unicode(" ".join(title))

    def get_alerts_preference(self, community_name):
        return self._alert_prefs.get(community_name, IProfile.ALERT_IMMEDIATELY)

    def set_alerts_preference(self, community_name, preference):
        if preference not in (IProfile.ALERT_IMMEDIATELY, IProfile.ALERT_DIGEST, IProfile.ALERT_NEVER):
            raise ValueError("Invalid preference.")

        self._alert_prefs[community_name] = preference

    def thumb_url(self, request, size=(46, 46)):
        if "photo" in self:
            return thumb_url(self["photo"], request, size)
        else:
            return request.api.static_url + "/img/default_user.png"

    @property
    def fullname(self):
        return self.firstname + " " + self.lastname
开发者ID:amarandon,项目名称:opencore,代码行数:95,代码来源:profile.py

示例10: MollieIdealPayment

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class MollieIdealPayment(object):
    implements(IMollieIdealPayment)
    adapts(IAttributeAnnotatable)

    def __init__(self, context):
        self.ideal_wrapper = getUtility(IMollieIdeal)
        annotations = IAnnotations(context)
        self._metadata = annotations.get(IDEAL_PAYMENT_ANNOTATION_KEY, None)
        if self._metadata is None:
            self._metadata = PersistentMapping()
            annotations[IDEAL_PAYMENT_ANNOTATION_KEY] = self._metadata

    # Properties

    def _getter(self, key):
        return self._metadata.get(key)

    def _setter(self, key, value):
        self._metadata[key] = value

    _partner_id = property(lambda self: self._getter('partner_id'),
        lambda self, value: self._setter('partner_id', value))

    _profile_key = property(lambda self: self._getter('profile_key'),
        lambda self, value: self._setter('profile_key', value))

    last_update = property(lambda self: self._getter('last_update'),
        lambda self, value: self._setter('last_update', value))

    transaction_id = property(lambda self: self._getter('transaction_id'),
        lambda self, value: self._setter('transaction_id', value))

    amount = property(lambda self: self._getter('amount'),
        lambda self, value: self._setter('amount', value))

    currency = property(lambda self: self._getter('currency'),
        lambda self, value: self._setter('currency', value))

    paid = property(lambda self: self._getter('paid'),
        lambda self, value: self._setter('paid', value))

    consumer = property(lambda self: self._getter('consumer'),
        lambda self, value: self._setter('consumer', value))

    status = property(lambda self: self._getter('status'),
        lambda self, value: self._setter('status', value))

    last_status = property(lambda self: self._getter('last_status'),
        lambda self, value: self._setter('last_status', value))

    # Methods

    def get_banks(self):
        return self.ideal_wrapper.get_banks()

    def get_payment_url(self, partner_id, bank_id, amount, message,
                        report_url, return_url, profile_key=None):
        transaction_id, url = self.ideal_wrapper.request_payment(
            partner_id, bank_id, amount, message, report_url,
            return_url, profile_key)

        self.transaction_id = transaction_id
        self._partner_id = partner_id
        self._profile_key = profile_key
        self.amount = amount
        self.last_update = DateTime()
        return url

    def get_payment_status(self):
        order_info = self.ideal_wrapper.check_payment(
            self._partner_id, self.transaction_id)
        if order_info['status'] != 'CheckedBefore':
            # Only store the main info the first time.
            self.currency = order_info['currency']
            self.paid = order_info['paid']
            self.consumer = order_info.get('consumer')
            self.status = order_info['status']
        self.last_status = order_info['status']
        self.last_update = DateTime()
        return self.last_status
开发者ID:collective,项目名称:collective.mollie,代码行数:82,代码来源:adapter.py

示例11: NotificationTool

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

#.........这里部分代码省略.........
                    'label': 'Rules on discussion item creation (users)',
                    'mode': 'w',
                    'type': 'lines'},
                   {'id': 'on_discussion_item_creation_mail_template',
                    'label': 'Rules on discussion item creation (mail template)',
                    'mode': 'w',
                    'type': 'lines'},
                   )

    security = ClassSecurityInfo()
    decPrivate = security.declarePrivate
    decProtected = security.declareProtected
    decPublic = security.declarePublic


    def __init__(self, *args, **kwargs):
        self._uid_to_path = PersistentMapping()
        self._subscriptions = PersistentMapping()


    #################################################################
    ## Notification handlers
    ########################
    decPrivate('onItemCreation')
    def onItemCreation(self, obj):
        """Handler called when an item is created.

        It returns the number of mails which have been sent.

        **Warning:** this handler is not called when a discussion item
        is added. In this case, ``onDiscussionItemCreation()`` is
        called instead.
        """
        if not self.getProperty('item_creation_notification_enabled'):
            return 0
        if self.ignoreNotification(obj):
            return 0

        extra_bindings = getBasicBindings(obj)
        extra_bindings.update({'current': obj,
                               'previous': None})
        return self._handlerHelper(obj, 'item_creation',
                                   extra_bindings,
                                   extra_bindings,
                                   extra_bindings)


    decPrivate('onItemModification')
    def onItemModification(self, obj):
        """Handler called when an item is modified.

        It returns the number of mails which have been sent.
        """
        if not self.getProperty('item_modification_notification_enabled'):
            return 0
        if self.ignoreNotification(obj):
            return 0

        extra_bindings = getBasicBindings(obj)
        extra_bindings.update({'current': obj,
                               'previous': self.getPreviousVersion(obj)})
        return self._handlerHelper(obj, 'item_modification',
                                   extra_bindings,
                                   extra_bindings,
                                   extra_bindings)
                                   
开发者ID:a25kk,项目名称:stv2,代码行数:69,代码来源:NotificationTool.py

示例12: CustomField

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class CustomField(Folder):
    """
    A CustomField is an object that becomes automatically included
    as part of the Add Issue page. The ID of the custom field becomes the
    name of the input. So if the ID is 'foo' the input rendered becomes
    <input name="foo">
    
    This class defines:
        
    Type of input
    ---------------------------------------------------------------------------
    
      You can select one of the following:
          text, textarea, password, hidden, select, checkbox, radio or file
          
      Depending on which one you select you'll specify parameters such as 
      'cols' (for type 'textarea' of course) or size. By having first selected
      a type, the field will autogenerate some default parameters that you can
      later modify.
    
    
    Default value
    ---------------------------------------------------------------------------
    
      The default value can be either a simple string inputted or it can be a
      reference to something else callable that will get the default value and
      this is done with a TALES expression. 
    
    Being mandatory or optional
    ---------------------------------------------------------------------------
    
      By default every field is optional but by making it mandatory, you'll 
      most likely going to have to specify a validation because sometimes it's 
      not as simple as checking that a value is boolean or not (e.g. bool(''))
    
    Validation
    ---------------------------------------------------------------------------
    
      This is where you specify either a reference to a script or a TALES 
      expression that will work out if a particular value is valid or not. 
    
    Javascript events hooks (onchange, onclick, onfocus, onblur)
    ---------------------------------------------------------------------------
    
      You'll be responsible for what you write in the values for these. The 
      values must be available javascript functions.
    
    Setting persistent values on issues
    ---------------------------------------------------------------------------
    
      (This is actually implemented in IssueTrackerProduct/IssueTracker.py)
    
      When saving the issue, we'll add an attribute to the issue like this::
          
          <id of custom field>: <value at input>
          
      This will pass through the validation a second time but unlike the first
      time, if the validation fails this time a hard error is raised. The type
      of the value is by default a unicode string or what else is appropriate 
      based on the input type. 
      You can specify an expression that will massage the input before it's 
      saved. So, suppose you want to save it as a floating point number you
      enter this expression::
          
          python:float(value)
          
    Getting persistent values on issues
    ---------------------------------------------------------------------------
    
      (This is actually implemented in IssueTrackerProduct/IssueTracker.py)

      You can ask the issuetracker for the value of a custom field simply by
      specifying the ID of the custom field and an optional default value. 
      Quite possibly you'll have an issuetracker where issues were added before
      the creation of the custom field so it'll be important to supply a 
      default value.
    
    Additionally loaded Javascript and CSS
    ---------------------------------------------------------------------------
    
      You get an area for entering the Javascript and the CSS and this is 
      automatically loaded on the Add Issue page. If you in your input of this
      (on the first line) enter a name of a file or DTML Method/Document that
      exists, that is instead rendered.
      The input can also be a valid URL if it looks relative and valid.
    
    """

    meta_type = CUSTOMFIELD_METATYPE

    manage_options = (
        {"label": "Manage", "action": "manage_field"},
        {"label": "Validation", "action": "manage_validation"},
    ) + Folder.manage_options

    _properties = (
        {"id": "title", "type": "ustring", "mode": "w"},
        {"id": "disabled", "type": "boolean", "mode": "w"},
        {"id": "python_type", "type": "selection", "mode": "w", "select_variable": "getOKPythonTypes"},
        {"id": "include_in_filter_options", "type": "boolean", "mode": "w"},
#.........这里部分代码省略.........
开发者ID:peterbe,项目名称:IssueTrackerProduct,代码行数:103,代码来源:CustomField.py

示例13: PSession

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [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

示例14: Box

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class Box(Persistent):
    implements(IDepositBox)

    def __init__(self, max_age=config.MAX_AGE, purge_days=config.PURGE_DAYS):
        self.data = PersistentMapping()
        self._last_purge = int(time.time())
        self.max_age = max_age
        self.purge_days = purge_days

    def _generate_new_id(self):
        """Generate new id.
        """
        new_id = id_generator()
        while new_id in self.data.keys():
            new_id = id_generator()
        return new_id

    def put(self, value, token=None):
        """Put value in box, with optional token, and return generated id.

        Calling this method also does a purge once a day (well, when
        the last purge was at least 24 hours ago).  The frequency can
        be controlled with the purge_days attribute.
        """
        cutoff = int(time.time()) - (self.purge_days * 86400)
        if self._last_purge < cutoff:
            self.purge()

        if value is None:
            raise ValueError
        id = self._generate_new_id()
        self.data[id] = BoxItem(token, value, confirmed=False)
        return id

    def edit(self, secret, value, token=None):
        """Edit value in the box, when secret and optional token match.
        """
        if value is None:
            raise ValueError
        stored = self.get(secret, token=token)
        if value == stored:
            # No change
            return
        self.data[secret] = BoxItem(token, value, confirmed=True)

    def get(self, secret, token=None):
        stored = self.data.get(secret)
        if stored is None:
            return None
        if stored.token != token:
            # raise Exception
            return None
        if not stored.confirmed:
            # Purge this item when it is expired:
            cutoff = int(time.time()) - self.max_age * 86400
            if stored.timestamp < cutoff:
                del self.data[secret]
                return None
            if token:
                # When there is a token, the item must be confirmed
                # before we return the value.  Main use case: email
                # confirmation.
                return None
        return stored.value

    def confirm(self, secret, token=None):
        """Confirm the item/token and return whether this succeeded or not.
        """
        stored = self.data.get(secret)
        if stored is None:
            return None
        if stored.token != token:
            # raise Exception?
            return None
        if not stored.confirmed:
            # First check if the confirmation comes too late.
            cutoff = int(time.time()) - self.max_age * 86400
            if stored.timestamp < cutoff:
                del self.data[secret]
                # Report back that we have failed, in case anyone
                # wants to know.
                return False
        stored.confirmed = True
        return True

    def pop(self, secret, token=None):
        stored = self.get(secret, token=token)
        if stored is None:
            return None
        self.data.pop(secret)
        return stored

    def get_all_confirmed(self):
        for key, stored in self.data.items():
            if stored.confirmed:
                yield stored.value

    def purge(self):
        """Purge items that have expired.

#.........这里部分代码省略.........
开发者ID:collective,项目名称:collective.depositbox,代码行数:103,代码来源:store.py

示例15: NounPhraseStorage

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import get [as 别名]
class NounPhraseStorage(Persistent):
    """A storage utility to keep noun-phrases in the ZODB.
    """
    
    implements(INounPhraseStorage)
    
    def __init__(self):
        """
        """
        self.rankedNouns = PersistentMapping()
        self.rankedNPs = PersistentMapping()
        self.extractor = getUtility(ITermExtractor)
        self.friendlyTypes = PersistentList()
    
    def _scoresToRanks(self,rankdict):
        scored_items = sorted(rankdict.items(),key=itemgetter(1),reverse=True)
        ranked_items = [
            ranked_item
            for ranked_item in
            ranks_from_scores(scored_items)]
        return ranked_items
    
    def addDocument(self,doc_id,text):
        """
        """
        (noun_scores,noun_phrase_scores) = self.extractor.extract(text)
        if noun_scores:
            ranked_nouns = self._scoresToRanks(noun_scores)
            self.rankedNouns[doc_id] = ranked_nouns
        if noun_phrase_scores:
            ranked_nps = self._scoresToRanks(noun_phrase_scores)
            self.rankedNPs[doc_id] = ranked_nps
    
    def _derankTerms(self,rankedTerms):
        return [term for (term,rank) in rankedTerms]
    
    def getRankedTerms(self,doc_id,ranksToKeep=0):
        """
        """
        ranked_nouns = self.rankedNouns.get(doc_id,[])
        ranked_nps = self.rankedNPs.get(doc_id,[])
        if ranksToKeep:
            ranked_nouns = [
                (noun,score)
                for (noun,score) in ranked_nouns
                if score < ranksToKeep]
            ranked_nps = [
                (np,score)
                for (np,score) in ranked_nps
                if score < ranksToKeep]
        
        return (ranked_nouns,ranked_nps)
    
    def getTerms(self,doc_id,ranksToKeep=0):
        (ranked_nouns,ranked_nps) = self.getRankedTerms(doc_id,ranksToKeep)
        ranked_nouns = self._derankTerms(ranked_nouns)
        ranked_nps = self._derankTerms(ranked_nps)
        return (ranked_nouns,ranked_nps)
    
    
    def getRankedNounTerms(self,doc_id,ranksToKeep=0):
        """
        """
        ranked_nouns = self.rankedNouns.get(doc_id,[])
        if ranksToKeep:
            ranked_nouns = [
                (noun,score)
                for (noun,score) in ranked_nouns
                if score < ranksToKeep]
        return ranked_nouns
    
    def getRankedNPTerms(self,doc_id,ranksToKeep=0):
        """
        """
        ranked_nps = self.rankedNPs.get(doc_id,[])
        if ranksToKeep:
            ranked_nps = [
                (np,score)
                for (np,score) in ranked_nps
                if score < ranksToKeep]
        
        return ranked_nps
    
    def getNounTerms(self,doc_id,ranksToKeep=0):
        ranked_nouns = self.getRankedTerms(doc_id,ranksToKeep)[0]
        ranked_nouns = self._derankTerms(ranked_nouns)
        return ranked_nouns
    
    def getNPTerms(self,doc_id,ranksToKeep=0):
        ranked_nps = self.getRankedTerms(doc_id,ranksToKeep)[1]
        ranked_nps = self._derankTerms(ranked_nps)
        return ranked_nps
    
    def clear(self):
        """Wipes the storage
        """
        self.rankedNouns.clear()
        self.rankedNPs.clear()
开发者ID:soerensigfusson,项目名称:collective.classification,代码行数:100,代码来源:npstorage.py


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