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


Python interfaces.ITranslationManager类代码示例

本文整理汇总了Python中plone.multilingual.interfaces.ITranslationManager的典型用法代码示例。如果您正苦于以下问题:Python ITranslationManager类的具体用法?Python ITranslationManager怎么用?Python ITranslationManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: _back_references

def _back_references(source_object, attribute_name, translation=None):
    catalog = getUtility(ICatalog)
    intids = getUtility(IIntIds)

    lang = queryAdapter(source_object, ILanguage).get_language()
    if translation:
        lang = queryAdapter(translation, ILanguage).get_language()

    gsm = getSecurityManager()
    result = []
    for rel in catalog.findRelations({
            'to_id': intids.getId(aq_inner(source_object)),
            'from_attribute':attribute_name
        }):
        obj = intids.queryObject(rel.from_id)
        if obj is not None and checkPermission('zope2.View', obj):
            if ITranslatable.providedBy(obj):
                trans_manager = ITranslationManager(aq_inner(obj))
                try:
                    trans_obj = trans_manager.get_translation(lang)
                except Unauthorized, e:
                    continue

                if trans_obj:
                    result.append(trans_obj)
                    continue

            if gsm.checkPermission('zope2.View', obj):
                result.append(obj)
开发者ID:oikoumene,项目名称:wcc.activity,代码行数:29,代码来源:backref.py

示例2: __call__

    def __call__(self):
        pc = getToolByName(self.context, "portal_catalog")
        pl = getToolByName(self.context, "portal_languages")
        self.results = []
        for language_supported in pl.getSupportedLanguages():
            translated_objects = pc.searchResults(object_provides=LP_TRANSLATABLE, Language=language_supported)
            for brain in translated_objects:
                obj = brain.getObject()
                if obj.isCanonical():
                    translations = obj.getTranslations(include_canonical=False)
                    manager = ITranslationManager(obj)
                    if translations:
                        for language in translations.keys():
                            try:
                                manager.register_translation(language, translations[language][0])
                            except KeyError:
                                logger.warning(
                                    "%s already translated to %s: %s"
                                    % (obj.id, language, str(manager.get_translations()))
                                )

                        self.results.append(str(manager.get_translations()))

        logger.info("Finished with transferring catalog information")
        return self.template()
开发者ID:pysailor,项目名称:plone.app.multilingual,代码行数:25,代码来源:migrator.py

示例3: _at_back_references

def _at_back_references(source_object, relationship, translation=None):

    lang = queryAdapter(source_object, ILanguage).get_language()
    if translation:
        lang = queryAdapter(translation, ILanguage).get_language()

    refs = IReferenceable(source_object).getBRefs(relationship=relationship)
    gsm = getSecurityManager()
    result = []
    for obj in refs:
        if ITranslatable.providedBy(obj):
            trans_manager = ITranslationManager(aq_inner(obj))
            try: 
                trans_obj = trans_manager.get_translation(lang)
            except Unauthorized:
                continue

            if trans_obj:
                result.append(trans_obj)
                continue

        if gsm.checkPermission('zope2.View', obj):
            result.append(obj)

    return result
开发者ID:oikoumene,项目名称:wcc.activity,代码行数:25,代码来源:backref.py

示例4: handle_unlink

 def handle_unlink(self, action):
     data, errors = self.extractData()
     manager = ITranslationManager(self.context)
     if not errors:
         for language in data["languages"]:
             manager.remove_translation(language)
     return self.request.response.redirect(self.context.absolute_url() + "/remove_translations")
开发者ID:radekj,项目名称:plone.app.multilingual,代码行数:7,代码来源:remove_translation_form.py

示例5: render

 def render(self):
     cat = getToolByName(self.context, 'portal_catalog')
     query = dict(portal_type='Folder', Language='en')
     res = cat(query)
     log.info('Total no. of folders found: {0}'.format(len(res)))
     links = dict()
     for r in res:
         if r.getPath().split('/')[2] != 'en':
             log.warning("Found a folder with lang EN not under /en: {0}".format(
                 r.getPath()))
             continue
         obj = r.getObject()
         if not ITranslatable.providedBy(obj):
             log.warning('Found a folder that is not translatable, WTF: {0}'.format(
                 r.getPath()))
             continue
         tm = ITranslationManager(obj)
         log.info('Handling folder {0}.'.format('/'.join(obj.getPhysicalPath())))
         for lang, trans in tm.get_translations().items():
             if lang == 'en':
                 continue
             # Copy "Exclude from navigation", section images and related sites
             trans.exclude_from_nav = obj.exclude_from_nav
             rsl = IRelatedSites(trans).related_sites_links
             if len(rsl):
                 links['/'.join(trans.getPhysicalPath())] = rsl
     return json.dumps(links)
开发者ID:EU-OSHA,项目名称:osha.hwccontent,代码行数:27,代码来源:helper.py

示例6: delete_this

def delete_this(ob, *args, **kw):
    err = list()
    lang = kw.get('lang', '')
    id_to_delete = kw['id_to_delete']
    name = ''

    if id_to_delete in ob.objectIds():
        name = id_to_delete
    else:
        # look for a translation of the item in the current language
        target_object = kw.get('target_object', None)
        if target_object:
            manager = ITranslationManager(target_object)
            trans_object = manager.get_translation(lang)
            if trans_object:
                name = trans_object.getId()

    if not name:
        err.append(u'No translation for language %s found' % lang)
    else:
        try:
            ob._delObject(name)
        except Exception, e:
            err.append(
                u'Could not delete %s for language %s. Message: %s'
                % (id_to_delete, lang, str(e)))
开发者ID:pysailor,项目名称:collective.multilingualtools,代码行数:26,代码来源:utils.py

示例7: renamer

def renamer(ob, *args, **kw):
    """ rename one object within context from oldid to newid """
    err = list()
    oldid = kw['oldid']
    newid = kw['newid']
    if not oldid:
        err.append(u'Current id must not be empty')
    else:
        oldid = oldid.encode('utf-8')
    if not newid:
        err.append(u'New id must not be empty')
    else:
        newid = newid.encode('utf-8')
    if not err:
        if oldid not in ob.objectIds():
            manager = ITranslationManager(kw['target_object'])
            trans = manager.get_translation(kw['lang'])
            if trans:
                oldid = trans.getId()
        if oldid in ob.objectIds():
            ob.manage_renameObjects([oldid], [newid])
        else:
            err.append(
                'No translation for %s in language %s found in '
                'folder %s' % (oldid, kw['lang'],
                '/'.join(ob.getPhysicalPath())))
    return err
开发者ID:pysailor,项目名称:collective.multilingualtools,代码行数:27,代码来源:utils.py

示例8: handle_modified

def handle_modified(self, content):

    fieldmanager = ILanguageIndependentFieldsManager(content)
    if not fieldmanager.has_independent_fields():
        return

    sm = getSecurityManager()
    try:
        # Do we have permission to sync language independent fields?
        if self.bypass_security_checks():
            # Clone the current user and assign a new editor role to
            # allow edition of all translated objects even if the
            # current user whould not have permission to do that.
            tmp_user = UnrestrictedUser(
                sm.getUser().getId(), '', ['Editor', ], '')

            # Wrap the user in the acquisition context of the portal
            # and finally switch the user to our new editor
            acl_users = getToolByName(content, 'acl_users')
            tmp_user = tmp_user.__of__(acl_users)
            newSecurityManager(None, tmp_user)

        # Copy over all language independent fields
        transmanager = ITranslationManager(content)
        for translation in self.get_all_translations(content):
            # PATCHED CODE HERE
            trans_obj = transmanager.get_restricted_translation(translation)
            if trans_obj:
                if fieldmanager.copy_fields(trans_obj):
                    self.reindex_translation(trans_obj)
            # END PATCHED CODE
    finally:
        # Restore the old security manager
        setSecurityManager(sm)
开发者ID:EU-OSHA,项目名称:osha.hwccontent,代码行数:34,代码来源:patch_pam.py

示例9: __call__

    def __call__(self):
        if (self.request.method != 'POST' and
            not ('field' in self.request.form.keys() and
                'lang_source' in self.request.form.keys())):
            return _("Need a field")
        else:
            manager = ITranslationManager(self.context)
            registry = getUtility(IRegistry)
            settings = registry.forInterface(IMultiLanguageExtraOptionsSchema)
            lang_target = ILanguage(self.context).get_language()
            lang_source = self.request.form['lang_source']
            orig_object = manager.get_translation(lang_source)
            try:
                question = orig_object.getField(
                    self.request.form['field']).get(orig_object)
            except AttributeError:
                return _("Invalid field")
            if len(question) > 1600:
                return _("Too long field")
            data = {'key': settings.google_translation_key,
                        'target': lang_target,
                        'source': lang_source,
                        'q': question}
            params = urllib.urlencode(data)

            url = 'https://www.googleapis.com/language/translate/v2'
            retorn = urllib.urlopen(url + '?' + params)
            return retorn.read()
开发者ID:adam139,项目名称:plone.app.multilingual,代码行数:28,代码来源:translate.py

示例10: handle_remove

 def handle_remove(self, action):
     data, errors = self.extractData()
     manager = ITranslationManager(self.context)
     if not errors:
         for language in data["languages"]:
             content = manager.get_translation(language)
             manager.remove_translation(language)
             aq_parent(content).manage_delObjects([content.getId()])
     return self.request.response.redirect(self.context.absolute_url() + "/remove_translations")
开发者ID:radekj,项目名称:plone.app.multilingual,代码行数:9,代码来源:remove_translation_form.py

示例11: idiomesIndexer

def idiomesIndexer(obj):
    llistat = []
    manager = ITranslationManager(obj)
    translations = manager.get_translations()
    for translation in translations:
        formula = translations[translation]
        for i in formula.items():
            llistat.append(i[1].Title())
    return llistat
开发者ID:iskracat,项目名称:mformulae,代码行数:9,代码来源:formules.py

示例12: _translations

    def _translations(self, missing):
        # Figure out the "closest" translation in the parent chain of the
        # context. We stop at both an INavigationRoot or an ISiteRoot to look
        # for translations. We do want to find something that is definitely
        # in the language the user asked for.
        context = aq_inner(self.context)
        translations = {}
        chain = aq_chain(context)
        first_pass = True
        _checkPermission = getSecurityManager().checkPermission
        for item in chain:
            if ISiteRoot.providedBy(item):
                # We have a site root, which works as a fallback
                has_view_permission = bool(_checkPermission('View', item))
                for c in missing:
                    translations[c] = (item, first_pass, has_view_permission)
                break

            elif IFactoryTempFolder.providedBy(item) or \
                    IFactoryTool.providedBy(item):
                # TempFolder or portal_factory, can't have a translation
                continue

            canonical = ITranslationManager(item, None)

            item_trans = canonical.get_translations()
            for code, trans in item_trans.items():
                code = str(code)
                if code not in translations:
                    # make a link to a translation only if the user
                    # has view permission
                    has_view_permission = bool(_checkPermission('View', trans))
                    if (not INavigationRoot.providedBy(item)
                            and not has_view_permission):
                        continue
                    # If we don't yet have a translation for this language
                    # add it and mark it as found
                    translations[code] = (trans, first_pass,
                            has_view_permission)
                    missing = missing - set((code, ))

            if len(missing) <= 0:
                # We have translations for all
                break
            if INavigationRoot.providedBy(item):
                # Don't break out of the navigation root jail
                has_view_permission = bool(_checkPermission('View', item))
                for c in missing:
                    translations[c] = (item, False, has_view_permission)
                break
            first_pass = False
        # return a dict of language code to tuple. the first tuple element is
        # the translated object, the second argument indicates wether the
        # translation is a direct translation of the context or something from
        # higher up the translation chain
        return translations
开发者ID:adam139,项目名称:plone.app.multilingual,代码行数:56,代码来源:selector.py

示例13: temesIndexer

def temesIndexer(obj):
    resultat = []
    temes = obj.temes
    for tema in temes:
        tema_obj = tema.to_object
        manager = ITranslationManager(tema_obj)
        translations = manager.get_translations()
        for translation in translations:
            resultat.append(translations[translation].id)
    return resultat
开发者ID:iskracat,项目名称:mformulae,代码行数:10,代码来源:formules.py

示例14: __call__

    def __call__(self):
        language = self.request.get('language', None)
        if language:
            context = aq_inner(self.context)
            translation_manager = ITranslationManager(context)
            if ILanguage(context).get_language() == LANGUAGE_INDEPENDENT:
                # XXX : Why we need this ? the subscriber from pm should maintain it
                language_tool = getToolByName(context, 'portal_languages')
                default_language = language_tool.getDefaultLanguage()
                ILanguage(context).set_language(default_language)
                translation_manager.update()
                context.reindexObject()

            new_parent = translation_manager.add_translation_delegated(language)

            registry = getUtility(IRegistry)
            settings = registry.forInterface(IMultiLanguageExtraOptionsSchema)
            sdm = self.context.session_data_manager
            session = sdm.getSessionData(create=True)
            session.set("tg", translation_manager.tg)

            baseUrl = new_parent.absolute_url()
            # We set the language and redirect to babel_view or not
            if settings.redirect_babel_view:
                # Call the ++addtranslation++ adapter to show the babel add form
                url = '%s/++addtranslation++%s' % (baseUrl, self.context.portal_type)
                return self.request.response.redirect(url)
            else:
                # We look for the creation url for this content type

                # Get the factory
                types_tool = getToolByName(self.context, 'portal_types')

                # Note: we don't check 'allowed' or 'available' here, because these are
                # slow. We assume the 'allowedTypes' list has already performed the
                # necessary calculations
                actions = types_tool.listActionInfos(
                    object=new_parent,
                    check_permissions=False,
                    check_condition=False,
                    category='folder/add',
                )

                addActionsById = dict([(a['id'], a) for a in actions])

                typeId = self.context.portal_type

                addAction = addActionsById.get(typeId, None)

                if addAction is not None:
                    url = addAction['url'] 

                if not url:
                    url = '%s/createObject?type_name=%s' % (baseUrl, quote_plus(typeId))
                return self.request.response.redirect(url)
开发者ID:agitator,项目名称:plone.app.multilingual,代码行数:55,代码来源:translate.py

示例15: test_multilingual_content_is_linked

    def test_multilingual_content_is_linked(self):
        english_content = self.portal.get('en').get('accessibility')
        self.assertTrue(english_content, 'Missing page /en/accessibility')

        german_content = self.portal.get('de').get('barrierefreiheit')
        self.assertTrue(german_content, 'Missing page /de/barrierefreiheit')

        manager = ITranslationManager(english_content)
        self.assertEquals(german_content,
                          manager.get_translation('de'),
                          'English and German content should be linked.')
开发者ID:maikroeder,项目名称:ftw.inflator,代码行数:11,代码来源:test_multilingual_content_creation.py


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