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


Python PersistentMapping.update方法代码示例

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


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

示例1: make_persistent

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
def make_persistent(value):
    """Counterpart to make_serializable().
    Recursively turns all dicts and lists into PersistentMappings respectively
    PersistentLists.
    """
    if isinstance(value, dict):
        retval = PersistentMapping()
        retval.update(value)
    elif isinstance(value, list):
        retval = PersistentList()
        for item in value:
            retval.append(item)
    else:
        retval = value
    return retval
开发者ID:4teamwork,项目名称:ftw.publisher.core,代码行数:17,代码来源:ftw_shop.py

示例2: populate

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
    def populate(self, db_factory):
        self._guarantee_min_random_data(self.objects_per_txn)

        db = db_factory()
        conn = db.open()
        root = conn.root()

        # clear the database
        root['speedtest'] = None
        # We explicitly leave the `speedtest_min` value around
        # so that it can survive packs.
        transaction.commit()
        db.pack()

        # Make sure the minimum objects are present
        if self.min_object_count:
            # not all storages support __len__ to return the size of the database.
            # FileStorage, RelStorage and ClientStorage do.
            db_count = max(len(db.storage), len(conn._storage))
            needed = max(self.min_object_count - db_count, 0)
            if needed:
                logger.debug("Adding %d objects to a DB of size %d",
                             needed, db_count)
                # We append to a list the new objects. This makes sure that we
                # don't *erase* some objects we were counting on.
                l = root.get('speedtest_min')
                if l is None:
                    l = root['speedtest_min'] = PersistentList()

                # If `needed` is large, this could result in a single
                # very large transaction. Do we need to think about splitting it up?
                m = PersistentMapping()
                m.update(self.data_to_store(needed))
                l.append(m)
                transaction.commit()
                logger.debug("Added %d objects to a DB of size %d",
                             len(m), db_count)
            else:
                logger.debug("Database is already of size %s", db_count)

        # put a tree in the database
        root['speedtest'] = t = self.MappingType()
        for i in range(self.concurrency):
            t[i] = self.MappingType()
        transaction.commit()
        conn.close()
        db.close()
        logger.debug('Populated storage.')
开发者ID:zodb,项目名称:zodbshootout,代码行数:50,代码来源:speedtest.py

示例3: Factory

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
class Factory(Container):
    """contains a number of Units. Takes a list of Units"""
    def __init__(self, data=None):
        super(Factory, self).__init__(data=data, max_size=1)
        self.produced = PersistentMapping()

    def __setitem__(self, key, val):
        super(Factory, self).__setitem__(key, val)
        self.produced.update({key.id: False})

    def __delitem__(self, key):
        super(Factory, self).__delitem__(key)
        del self.produced[key.id]

    def append(self, item):
        super(Factory, self).append(self, item)
        self.produced.update({item.id: False})

    def upgrade(self):
        self.max_size += 1

    def reset(self):
        self.produced = {unit.id: False for unit in self.data}
开发者ID:AFDudley,项目名称:equanimity,代码行数:25,代码来源:factory.py

示例4: init_locs

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
 def init_locs(self):
     #calling this in init is most likely not going to work as intended.
     locs = PersistentMapping()
     for u in self['units'].keys():
         locs.update({u: self['units'][u].location})
     return locs
开发者ID:jessetane,项目名称:btpy,代码行数:8,代码来源:zodb_hex_battle.py

示例5: PasswordResetTool

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
class PasswordResetTool(SimpleItem):
    meta_type = 'Eionet Password Reset Tool'
    security = ClassSecurityInfo()
    icon = '++resource++eea.ldapadmin-www/eionet_password_reset_tool.gif'
    session_messages = SESSION_MESSAGES

    manage_options = (
        {'label': 'Configure', 'action': 'manage_edit'},
        {'label': 'View', 'action': ''},
    ) + SimpleItem.manage_options

    _render_template = TemplateRenderer(CommonTemplateLogic)

    def __init__(self, config={}):
        super(PasswordResetTool, self).__init__()
        self._config = PersistentMapping(config)
        self._tokens = PersistentMapping()

    security.declareProtected(view_management_screens, 'get_config')

    def get_config(self):
        return dict(self._config)

    security.declareProtected(view_management_screens, 'manage_edit')
    manage_edit = PageTemplateFile('zpt/pwreset_manage_edit', globals())
    manage_edit.ldap_config_edit_macro = ldap_config.edit_macro

    security.declareProtected(view_management_screens, 'manage_edit_save')

    def manage_edit_save(self, REQUEST):
        """ save changes to configuration """
        form = REQUEST.form
        new_config = ldap_config.read_form(form, edit=True)

        new_config['legacy_ldap_server'] = form.get('legacy_ldap_server', '')
        new_config['legacy_admin_dn'] = form.get('legacy_admin_dn', '')
        new_config['legacy_admin_pw'] = form.get('legacy_admin_pw', '')
        if not new_config['legacy_admin_pw']:
            del new_config['legacy_admin_pw']  # don't overwrite

        self._config.update(new_config)
        REQUEST.RESPONSE.redirect(self.absolute_url() + '/manage_edit')

    def _get_ldap_agent(self, bind=True):
        return ldap_config.ldap_agent_with_config(self._config, bind)

    def _predefined_filters(self):
        return sorted(self.objectValues([query.Query.meta_type]),
                      key=lambda ob: ob.getId())

    security.declareProtected(view, 'index_html')

    def index_html(self, REQUEST):
        """ view """
        email = REQUEST.get('email', '')
        options = {'email': email}
        return self._render_template('zpt/pwreset_index.zpt', **options)

    def _new_token(self, user_id):
        token = random_token()
        self._tokens[token] = TokenData(user_id, datetime.utcnow())
        return token

    def _send_token_email(self, addr_to, token, user_info):
        addr_from = "[email protected]"
        email_template = load_template('zpt/pwreset_token_email.zpt')
        expiration_time = datetime.utcnow() + timedelta(days=1)
        options = {
            'token_url': self.absolute_url() + "/confirm_email?token=" + token,
            'user_info': user_info,
            'context': self,
            'network_name': NETWORK_NAME,
            'expiration_time': expiration_time.strftime("%Y-%m-%d %H:%M:%S")
        }
        print options['token_url']
        message = MIMEText(email_template(**options).encode('utf-8'),
                           _charset='utf-8')
        message['From'] = addr_from
        message['To'] = addr_to
        message['Subject'] = "%s account password recovery" % NETWORK_NAME

        try:
            mailer = getUtility(IMailDelivery, name="Mail")
            mailer.send(addr_from, [addr_to], message.as_string())
        except ComponentLookupError:
            mailer = getUtility(IMailDelivery, name="naaya-mail-delivery")
            try:
                mailer.send(addr_from, [addr_to], message.as_string())
            except AssertionError:
                mailer.send(addr_from, [addr_to], message)

    security.declareProtected(view, 'ask_for_password_reset')

    def ask_for_password_reset(self, REQUEST=None, email=None):
        """ view """
        if REQUEST is None:
            REQUEST = self.REQUEST
        if not email:
            email = REQUEST.form['email']

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

示例6: OrganisationsEditor

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
class OrganisationsEditor(SimpleItem, PropertyManager):
    meta_type = 'Eionet Organisations Editor'
    security = ClassSecurityInfo()
    icon = '++resource++eea.ldapadmin-www/eionet_organisations_editor.gif'
    session_messages = SESSION_MESSAGES
    manage_options = (
        {'label': 'Configure', 'action': 'manage_edit'},
        {'label': 'View', 'action': ''},
    ) + PropertyManager.manage_options + SimpleItem.manage_options

    _properties = (
        {'id': 'title', 'type': 'string', 'mode': 'w', 'label': 'Title'},
    )

    _render_template = TemplateRenderer(CommonTemplateLogic)

    def _set_breadcrumbs(self, stack):
        self.REQUEST._orgs_editor = stack

    def breadcrumbtrail(self):
        crumbs_html = self.aq_parent.breadcrumbtrail(self.REQUEST)
        extra_crumbs = getattr(self.REQUEST, '_orgs_editor', [])
        return extend_crumbs(crumbs_html, self.absolute_url(), extra_crumbs)

    def __init__(self, config={}):
        super(OrganisationsEditor, self).__init__()
        self._config = PersistentMapping(config)

    security.declareProtected(view_management_screens, 'get_config')

    def get_config(self):
        return dict(self._config)

    security.declareProtected(view_management_screens, 'manage_edit')
    manage_edit = PageTemplateFile('zpt/orgs_manage_edit', globals())
    manage_edit.ldap_config_edit_macro = ldap_config.edit_macro

    security.declarePublic('checkPermissionView()')

    def checkPermissionView(self):
        user = self.REQUEST.AUTHENTICATED_USER
        return bool(user.has_permission(view, self))

    security.declareProtected(view, 'can_edit_organisation')

    def can_edit_organisation(self):
        user = self.REQUEST.AUTHENTICATED_USER
        if user.has_permission(eionet_edit_orgs, self):
            return True
        nfp_country = self.nfp_for_country()
        if nfp_country:
            agent = self._get_ldap_agent()
            org_id = self.REQUEST.form.get('id')
            org_info = agent.org_info(org_id)
            if nfp_country == 'eea':
                return org_info['country'] in ['eu', 'int']
            else:
                return nfp_country == org_info['country']

    security.declarePublic('checkPermissionEditOrganisations()')

    def checkPermissionEditOrganisations(self):
        user = self.REQUEST.AUTHENTICATED_USER
        return bool(user.has_permission(eionet_edit_orgs, self))

    security.declarePublic('can_edit_organisations')

    def can_edit_organisations(self):
        return bool(self.checkPermissionEditOrganisations() or
                    self.nfp_for_country())

    security.declareProtected(view_management_screens, 'manage_edit_save')

    def manage_edit_save(self, REQUEST):
        """ save changes to configuration """
        self._config.update(ldap_config.read_form(REQUEST.form, edit=True))
        REQUEST.RESPONSE.redirect(self.absolute_url() + '/manage_edit')

    def _get_ldap_agent(self, bind=True, secondary=False):
        agent = ldap_config.ldap_agent_with_config(self._config, bind,
                                                   secondary=secondary)
        agent._author = logged_in_user(self.REQUEST)
        return agent

    def index_html(self, REQUEST):
        """ Index of organisations """
        country = REQUEST.get('country')
        nfp_country = self.nfp_for_country()
        if self.title != 'National Organisations':
            nfp_country = None
        if not (self.checkPermissionView() or nfp_country):
            raise Unauthorized
        agent = self._get_ldap_agent(secondary=True)
        orgs_by_id = agent.all_organisations()
        countries = dict(get_country_options(country=nfp_country or country))
        orgs = []
        for org_id, info in orgs_by_id.iteritems():
            country = countries.get(info['country'])
            if country:
                orgs.append({'id': org_id,
#.........这里部分代码省略.........
开发者ID:eea,项目名称:eea.ldapadmin,代码行数:103,代码来源:orgs_editor.py

示例7: Notifier

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

    implements(INotifier)

    valid_headers = ('Subject', 'From', 'To')

    def __init__(self):
        self.subject = None
        self.signature = None
        self.comment_edited_text = None
        self.comment_deleted_text = None
        self.subscription_comment_added_text = None
        self.subscription_comment_edited_text = None
        self.thread_moved_text = None
        self._salutations = PersistentMapping()

    def get_salutations(self):
        return self._salutations

    def set_salutations(self, mapping):
        if isinstance(mapping, PersistentMapping):
            self._salutations = mapping
        else:
            self._salutations = PersistentMapping()
            self._salutations.update(mapping)

    salutations = property(get_salutations, set_salutations)

    def _salutation_for_member(self, mdata):
        """
        answer an appropriate salutation
        """
        key = mdata.get('salutation', '')
        return self.salutations.get(key, '') % mdata

    @staticmethod
    def _encoding():
        return getUtility(ISiteRoot).getProperty('email_charset', 'utf-8')

    def _notify(self, mdata, text):
        headers = {}
        headers.update([tp for tp in HeaderParser().parsestr(text.encode(self._encoding())).items() if tp[0] in self.valid_headers])
        if headers.keys():
            text = '\n\n'.join(text.split('\n\n')[1:])
        msg = MIMEText(text, _charset=self._encoding())
        msg['Subject'] = self.subject
        msg['From'] = getUtility(ISiteRoot).email_from_address
        msg['To'] = mdata.get('email')
        for k, v in headers.items():
            msg.replace_header(k, v)
        mh = getUtility(IMailHost)
        mh.send(msg)

    def _thread_info(self, thread):
        di = {}
        di['threadtitle'] = thread.Title().decode(self._encoding())
        di['threadurl'] = thread.absolute_url()
        di['boardtitle'] = thread.getForum().Title().decode(self._encoding())
        di['mailsignature'] = self.signature
        return di

    @classmethod
    def _memberdata_for_content(cls, content):
        return cls._memberdata_for(content.Creator())

    @classmethod
    def _memberdata_for(cls, memberid):
        site = getUtility(ISiteRoot)
        mtool = getToolByName(site, 'portal_membership')
        mdtool = getToolByName(site, 'portal_memberdata')
        keys = mdtool.propertyIds()
        mdata = mtool.getMemberById(memberid)
        if mdata is None: # no memberdata, most likely the user has been deleted
            return
        result = {}
        result.update([(k, str(mdata.getProperty(k)).decode(cls._encoding())) for k in keys])
        return result

    def comment_edited(self, comment):
        """
        a comment has been edited. Notify the creator of the comment.
        """
        # do not notify the creator if she has edited the comment herself
        mtool = getToolByName(comment, 'portal_membership')
        member = mtool.getAuthenticatedMember()
        creator = mtool.getMemberById(comment.Creator())
        if (member == creator) or creator is None or not self.comment_edited_text or not self.comment_edited_text.strip():
            return
        thread = comment.getConversation()
        di = self._thread_info(thread)
        di.update(self._memberdata_for_content(comment))
        di['salutation'] = self._salutation_for_member(di)
        di['commenturl'] = comment.absolute_url()
        self._notify(di, self.comment_edited_text % di)
        log.info('comment %s has been edited, notified owner %s' % (di['commenturl'], di.get('email')))

    def thread_moved(self, thread):
        """
        a thread has been moved to a new board. Notify all contributors.
        """
#.........这里部分代码省略.........
开发者ID:erral,项目名称:hl.plone.boardnotifications,代码行数:103,代码来源:notify.py

示例8: update

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
 def update(self, dict):
     for k in dict.keys():
         if not self.data.has_key(k):
             self._keys.append(k)
     return BaseDict.update(self, dict)
开发者ID:socialplanning,项目名称:topp.utils,代码行数:7,代码来源:orderedpersistentmapping.py

示例9: add_doc_status

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
 def add_doc_status(self, document_id, status_data):
     doc_status = PersistentMapping()
     doc_status.update(status_data)
     self._data['documents'][document_id] = doc_status
开发者ID:4teamwork,项目名称:opengever.core,代码行数:6,代码来源:zipexport.py

示例10: NfpNrc

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
class NfpNrc(SimpleItem, PropertyManager):
    meta_type = 'Eionet NFP Admin'
    security = ClassSecurityInfo()
    icon = '++resource++eea.ldapadmin-www/eionet_nfp_admin.gif'
    session_messages = SESSION_MESSAGES

    manage_options = (
        {'label': 'Configure', 'action': 'manage_edit'},
        {'label': 'View', 'action': ''},
    ) + PropertyManager.manage_options + SimpleItem.manage_options

    _properties = (
        {'id': 'title', 'type': 'string', 'mode': 'w', 'label': 'Title'},
    )

    _render_template = TemplateRenderer(CommonTemplateLogic)
    _render_template_no_wrap = TemplateRendererNoWrap(CommonTemplateLogic)

    security.declareProtected(view_management_screens, 'manage_edit')
    manage_edit = PageTemplateFile('zpt/nfp_nrc/manage_edit', globals())
    manage_edit.ldap_config_edit_macro = ldap_config.edit_macro

    def __init__(self, config={}):
        super(NfpNrc, self).__init__()
        self._config = PersistentMapping(config)

    def _set_breadcrumbs(self, stack):
        self.REQUEST._nfp_nrc = stack

    def breadcrumbtrail(self):
        crumbs_html = self.aq_parent.breadcrumbtrail(self.REQUEST)
        extra_crumbs = getattr(self.REQUEST, '_nfp_nrc', [])
        return extend_crumbs(crumbs_html, self.absolute_url(), extra_crumbs)

    security.declarePrivate('_allowed')

    def _allowed(self, agent, request, country_code):
        """
        Tests if logged in user is allowed to manage NRC members for
        `country` (whether he is an NFP member for country)

        """
        uid = _get_user_id(request)
        filterstr = ("(&(objectClass=groupOfUniqueNames)(uniqueMember=%s))" %
                     agent._user_dn(uid))
        nfp_roles = agent.filter_roles("eionet-nfp-*-%s" % country_code,
                                       prefix_dn="cn=eionet-nfp,cn=eionet",
                                       filterstr=filterstr,
                                       attrlist=("description",))
        if not (bool(nfp_roles) or self.checkPermissionZopeManager()):
            _set_session_message(
                request, 'error',
                "You are not allowed to manage NRC members for %s"
                % code_to_name(country_code))
            request.RESPONSE.redirect(self.absolute_url())
            return False
        else:
            return True

    security.declareProtected(view_management_screens, 'get_config')

    def get_config(self):
        return dict(self._config)

    security.declareProtected(view_management_screens, 'manage_edit_save')

    def manage_edit_save(self, REQUEST):
        """ save changes to configuration """
        self._config.update(ldap_config.read_form(REQUEST.form, edit=True))
        REQUEST.RESPONSE.redirect(self.absolute_url() + '/manage_edit')

    def _get_ldap_agent(self, bind=True, secondary=False):
        agent = ldap_config.ldap_agent_with_config(self._config, bind,
                                                   secondary=secondary)
        try:
            agent._author = logged_in_user(self.REQUEST)
        except AttributeError:
            agent._author = "System user"
        return agent

    security.declareProtected(view, 'index_html')

    def index_html(self, REQUEST):
        """ view """
        if not _is_authenticated(REQUEST):
            return self._render_template('zpt/nfp_nrc/index.zpt')
        agent = self._get_ldap_agent()
        user_id = logged_in_user(REQUEST)
        nfps = get_nfp_roles(agent, user_id)
        options = {'nfps': nfps}
        return self._render_template('zpt/nfp_nrc/index.zpt', **options)

    def get_top_role_members(self, role_dn, country_code):
        """ """
        agent = self._get_ldap_agent()
        has_problematic_users = False
        top_role_id = agent._role_id(role_dn)
        filter_country = "%s-*-%s" % (top_role_id, country_code)
        roles = []
        for (role_dn, attr) in agent.conn.search_s(
#.........这里部分代码省略.........
开发者ID:eea,项目名称:eea.ldapadmin,代码行数:103,代码来源:nfp_nrc.py

示例11: UITool

# 需要导入模块: from persistent.mapping import PersistentMapping [as 别名]
# 或者: from persistent.mapping.PersistentMapping import update [as 别名]
class UITool(UniqueObject, SimpleItem):
    """ The UITool handles creation and loading of ui themes. """

    implements(IUITool)
    id = 'portal_ui_tool'

    ## implement the fields, given through the interfaces
    theme = ''
    download = ''
    themeroller = ''
    themeHashes = None

    def cp_js_translations(self):
        """ return some translated js strings """
        return u'var sorry_only_firefox = "%s";\n' \
            u'var nothing_themed = "%s";\n' \
            u'var name_missing = "%s";\n' \
            u'var no_sunburst_name = "%s";\n' \
            u'var no_special_chars = "%s";\n\n' % (
            translate(_(u"Sorry, due to security restrictions, this tool " \
                            u"only works in Firefox"),
                      domain='zettwerk.ui',
                      context=self.REQUEST),
            translate(_(u"Download name given but nothing themed - please " \
                            "use themeroller"),
                      domain='zettwerk.ui',
                      context=self.REQUEST),
            translate(_(u"You opened themeroller, but no download name is " \
                            u"given. Click ok to continue and ignore your " \
                            u"changes or click cancel to enter a name."),
                      domain='zettwerk.ui',
                      context=self.REQUEST),
            translate(_(u"Sorry, sunburst is an invalid name"),
                      domain='zettwerk.ui',
                      context=self.REQUEST),
            translate(_(u"Please use no special characters."),
                      domain='zettwerk.ui',
                      context=self.REQUEST),
            )

    def css(self, *args):
        """ Generate the css rules, suitable for the given settings. """
        content_type_header = 'text/css;charset=UTF-8'
        self.REQUEST.RESPONSE.setHeader('content-type',
                                        content_type_header)
        result = ""

        if self.theme:
            ## the sunburst resource in portal_css is disabled
            ## cause enable/disabling resources in service mode
            ## seems not to work as i expect
            if self.theme == u'sunburst':
                result += '@import "++resource++jquery-ui-themes/' \
                    'sunburst/jqueryui.css";'
            else:
                resource_base = '++resource++zettwerk.ui.themes'
                css_filename = 'jquery.ui.theme.css';
                if isCustomTheme(self.theme):
                    css_filename = 'jquery-ui-1.9.2.custom.css'
                result += '@import "%s/%s/%s";' % (
                    resource_base,
                    self.theme,
                    css_filename
                    )

        return result

    def _redirectToCPView(self, msg=None):
        """ Just a redirect. """
        if msg is not None:
            utils = getToolByName(self, 'plone_utils')
            utils.addPortalMessage(msg)

        portal_url = getToolByName(self, 'portal_url')
        url = '%s/%s/@@ui-controlpanel' % (portal_url(),
                                           self.getId())
        return self.REQUEST.RESPONSE.redirect(url)

    def _rebuildThemeHashes(self):
        """ For edit existing themes, the hash is needed. They are stored
        in self.themeHashes. The problem with this: by quick-reinstalling
        zettwerk.ui this attribute get None. Also, if new themes were
        copied 'by hand' (as described in the README for deploying) the
        themeHashes doesn't know the copied theme's hash. This method
        reads all available themes and the theme-custom.css file to rebuild
        the themeHashes attribute. Its called every time the control panel
        view is called. """
        if self.themeHashes is None:
            self.themeHashes = PersistentMapping()

        theme_dirs = getDirectoriesOfDownloadHome()
        for theme_dir in theme_dirs:
            theme_hash = getThemeHashOfCustomCSS(theme_dir)
            if theme_hash:
                self.themeHashes.update({theme_dir: theme_hash})
        self._handleSunburst()

    def _handleSunburst(self):
        """" since we support collective.js.jqueryui, it would make
        sense to add the provided sunburst theme as a theme, too. """
#.........这里部分代码省略.........
开发者ID:collective,项目名称:zettwerk.ui,代码行数:103,代码来源:tool.py

示例12: Notifier

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

    implements(INotifier)

    valid_headers = ('Subject', 'From', 'To')

    def __init__(self):
        self.subject = None
        self.signature = None
        self.comment_edited_text = None
        self.comment_deleted_text = None
        self.subscription_comment_added_text = None
        self.subscription_comment_edited_text = None
        self.thread_moved_text = None
        self._salutations = PersistentMapping()

    def create_plaintext_message(self, text):
        """ Create a plain-text-message by parsing the html
            and attaching links as endnotes

            Modified from EasyNewsletter/content/ENLIssue.py
        """
        # This reflows text which we don't want, but it creates
        # parser.anchorlist which we do want.
        textout = StringIO.StringIO()
        formtext = formatter.AbstractFormatter(formatter.DumbWriter(textout))
        parser = HTMLParser(formtext)
        parser.feed(text)
        parser.close()

        # append the anchorlist at the bottom of a message
        # to keep the message readable.
        counter = 0
        anchorlist = "\n\n" + '----' + "\n\n"
        for item in parser.anchorlist:
            counter += 1
            anchorlist += "[%d] %s\n" % (counter, item)

        # This reflows text:
        # text = textout.getvalue() + anchorlist
        # This just strips tags, no reflow
        text = html.fromstring(text).text_content()
        text += anchorlist
        del textout, formtext, parser, anchorlist
        return text

    def get_salutations(self):
        return self._salutations

    def set_salutations(self, mapping):
        if isinstance(mapping, PersistentMapping):
            self._salutations = mapping
        else:
            self._salutations = PersistentMapping()
            self._salutations.update(mapping)

    salutations = property(get_salutations, set_salutations)

    def _salutation_for_member(self, mdata):
        """
        answer an appropriate salutation
        """
        key = mdata.get('salutation', '')
        return self.salutations.get(key, '') % mdata

    @staticmethod
    def _encoding():
        return getUtility(ISiteRoot).getProperty('email_charset', 'utf-8')

    def _notify(self, mdata, text):
        to_email = mdata.get('email')
        if not to_email:
            log.info('Cannot send notification e-mail because there\'s no destination.')
            return

        headers = {}
        headers.update([tp for tp in HeaderParser().parsestr(text.encode(self._encoding())).items() if tp[0] in self.valid_headers])
        if headers.keys():
            text = '\n\n'.join(text.split('\n\n')[1:])
        text = self.create_plaintext_message(text)
        msg = MIMEText(text, _charset=self._encoding())
        msg['Subject'] = self.subject
        msg['From'] = getUtility(ISiteRoot).email_from_address
        msg['To'] = to_email
        for k, v in headers.items():
            msg.replace_header(k, v)
        mh = getUtility(IMailHost)
        mh.send(msg)

    def _thread_info(self, thread):
        di = {}
        di['threadtitle'] = thread.Title().decode(self._encoding())
        di['threadurl'] = thread.absolute_url()
        di['boardtitle'] = thread.getForum().Title().decode(self._encoding())
        di['mailsignature'] = self.signature
        return di

    @classmethod
    def _memberdata_for_content(cls, content):
        return cls._memberdata_for(content.Creator())
#.........这里部分代码省略.........
开发者ID:Haufe-Lexware,项目名称:hl.plone.boardnotifications,代码行数:103,代码来源:notify.py


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