Esempio n. 1
0
    def children(self):
        group_id = self._request.params.get('group_id', None)
        path = self._request.params.get('path', '')

        client_tsf = TranslationStringFactory('{}-client'.format(
            self._request.registry.package_name))

        if group_id is None:
            items = self._dbsession.query(Theme). \
                order_by(Theme.ordering)
        else:
            items = self._dbsession.query(TreeItem). \
                join(TreeItem.parents_relation). \
                filter(LayergroupTreeitem.treegroup_id == group_id)

        return [{
            'id':
            item.id,
            'item_type':
            item.item_type,
            'name':
            item.name,
            'translated_name':
            self._request.localizer.translate(client_tsf(item.name)),
            'description':
            item.description,
            'path':
            '{}_{}'.format(path, item.id),
            'parent_path':
            path,
            'actions': [
                action.to_dict(self._request)
                for action in self._item_actions(item, group_id)
            ]
        } for item in items]
Esempio n. 2
0
    def children(self) -> List[Dict[str, Any]]:
        group_id = self._request.params.get("group_id", None)
        path = self._request.params.get("path", "")

        client_tsf = TranslationStringFactory("{}-client".format(
            self._request.registry.package_name))

        if group_id is None:
            items = self._dbsession.query(Theme).order_by(Theme.ordering)
        else:
            items = (
                self._dbsession.query(TreeItem).join(TreeItem.parents_relation)  # pylint: disable=no-member
                .filter(LayergroupTreeitem.treegroup_id == group_id))

        return [{
            "id":
            item.id,
            "item_type":
            item.item_type,
            "name":
            item.name,
            "translated_name":
            self._request.localizer.translate(client_tsf(item.name)),
            "description":
            item.description,
            "path":
            "{}_{}".format(path, item.id),
            "parent_path":
            path,
            "actions": [
                action.to_dict(self._request)
                for action in self._item_actions(item, group_id)
            ],
        } for item in items]
Esempio n. 3
0
 def serialize(self, field, cstruct, readonly=False, **kw):
     if cstruct is null:
         cstruct = u''
     values = self.get_template_values(field, cstruct, kw)
     # make `_` available in template for i18n messages
     values['_'] = TranslationStringFactory('c2cgeoform')
     values['widget_config'] = json.dumps({
         'labelField': self.label_field,
         'url': self.url,
         'readonly': readonly
     })
     return field.renderer('map_select', **values)
Esempio n. 4
0
    def children(self) -> List[Dict[str, Any]]:
        interface = self._request.params.get("interface", None)
        group_id = self._request.params.get("group_id", None)
        path = self._request.params.get("path", "")

        client_tsf = TranslationStringFactory(
            f"{self._request.registry.package_name}-client")

        if group_id is None:
            items = self._dbsession.query(Theme).order_by(Theme.ordering)
            if interface is not None:
                items = items.join(
                    Theme.interfaces).filter(Interface.name == interface)

        else:
            items = (self._dbsession.query(TreeItem).join(
                TreeItem.parents_relation).filter(
                    LayergroupTreeitem.treegroup_id == group_id).order_by(
                        LayergroupTreeitem.ordering))

        return [
            {
                "id":
                item.id,
                "item_type":
                item.item_type,
                "name":
                item.name,
                "translated_name":
                self._request.localizer.translate(client_tsf(item.name)),
                "description":
                item.description,
                "path":
                f"{path}_{item.id}",
                "parent_path":
                path,
                "actions": [
                    action.to_dict(self._request)
                    for action in self._item_actions(item, group_id)
                ],
            } for item in items
            if interface is None or not isinstance(item, Layer)
            or interface in [interface.name for interface in item.interfaces]
        ]
Esempio n. 5
0
    authenticated_userid,
)
from pyramid.threadlocal import get_current_request
#from pyramid_mailer import get_mailer
#from pyramid_mailer.message import Message
from translationstring import TranslationStringFactory
#from types import NoneType
from trytond.transaction import Transaction
from trytond.exceptions import UserError as TrytonUserError

deform_templates = resource_filename('deform', 'templates')
c3smembership_templates = resource_filename('c3sadoportal', 'templates')

my_search_path = (deform_templates, c3smembership_templates)

_ = TranslationStringFactory('c3sadoportal')


def translator(term):
    return get_localizer(get_current_request()).translate(term)


my_template_dir = resource_filename('c3sadoportal', 'templates/')
deform_template_dir = resource_filename('deform', 'templates/')

zpt_renderer = deform.ZPTRendererFactory(
    [
        my_template_dir,
        deform_template_dir,
    ],
    translator=translator,
Esempio n. 6
0
from logging import getLogger

from pyramid.config import Configurator
from pyramid_zodbconn import get_connection
from translationstring import TranslationStringFactory

from .models.appmaker import appmaker

_ = TranslationStringFactory('kedja')
logger = getLogger(__name__)


def root_factory(request):
    conn = get_connection(request)
    return appmaker(conn.root(), request)


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    with Configurator(settings=settings) as config:
        config.include('kedja')
        config.include('.views')
    return config.make_wsgi_app()


def includeme(config):
    """ Include all locals except views. Useful for integration/functional tests too. """
    # Some sensible defaults
    settings = config.registry.settings
    settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'
Esempio n. 7
0
import json
import logging

import colander as c
import deform.widget as w
from deform.exception import ValidationFailure
from deform.form import Form as _Form
from pyramid_deform import FormView as _FormView, CSRFSchema
from pyramid.view import view_config
from translationstring import TranslationStringFactory

from libweasyl.legacy import login_name
from libweasyl.models.users import Login
from .decorators import wraps_respecting_view_config

_ = TranslationStringFactory(__name__)
log = logging.getLogger(__name__)


def determine_errors(exc):
    """
    Pull out all of the error messages from a
    :py:class:`~deform.ValidationFailure`.

    This iterates over all of the error nodes in the underlying
    :py:class:`~colander.Invalid`, using :py:meth:`~colander.Invalid.paths`.
    Importantly, this calls (the apparently undocumented)
    :py:func:`colander.interpolate` on each error message, producing error
    messages without ``${}`` in them.

    :param exc: A :py:class:`deform.ValidationFailure`.
Esempio n. 8
0
# Global importsA
import colander
from translationstring import TranslationStringFactory
import pytz
_ = TranslationStringFactory('deform')

# Local import
from facile.forms.Deform import Form
utc = pytz.UTC


class DocumentForm(Form):
    def __init__(self, request, static_path, **kwargs):

        self.mapping_name = {'index': None, 'document': None}

        Form.__init__(self,
                      request,
                      static_path,
                      self.get_schema(kwargs['nodes']),
                      buttons=('Editer le document', ))

    @staticmethod
    def get_schema(l_nodes):
        schema_ = colander.Schema()
        for node in l_nodes:
            schema_.add(node)

        return schema_
Esempio n. 9
0
 def _makeOne(self, domain):
     from translationstring import TranslationStringFactory
     return TranslationStringFactory(domain)
Esempio n. 10
0
"""
use as import:
from nive_userdb.i18n import _
"""
from translationstring import TranslationStringFactory

_ = TranslationStringFactory('nive_userdb')

from nive.i18n import translator
from nive.i18n import translate
Esempio n. 11
0
""" Form and Field Interfaces """
from zope import interface
from pyramid.i18n import get_localizer
from pyramid.threadlocal import get_current_request
from translationstring import TranslationStringFactory

MessageFactory = _ = TranslationStringFactory('ptah.form')


class Invalid(Exception):
    """An exception raised by data types and validators indicating that
    the value for a particular field was not valid.

    ``msg``: Error message

    ``field``: Field object

    ``mapping``: Mapping for translate message interpolation

    ``name``: Custom error name

    ``errors``: Sub errors
    """
    def __init__(self,
                 msg='',
                 field=None,
                 mapping=None,
                 name=None,
                 errors=None):
        self.msg = msg
        self.field = field
Esempio n. 12
0
def translator(term, domain='deform'):
    """hooks into pyramid's translation infrastructure to translate `term`"""
    if not hasattr(term, 'interpolate'):  # not a translation string
        term = TranslationStringFactory(domain)(term)
    return get_localizer(get_current_request()).translate(term)
Esempio n. 13
0
"""
use as import:
from nive_cms.i18n import _
"""
from translationstring import TranslationStringFactory
_ = TranslationStringFactory('nive_cms')

from nive.i18n import translator
from nive.i18n import translate
Esempio n. 14
0
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import absolute_import
from __future__ import unicode_literals

from translationstring import TranslationStringFactory
import colander

from .core import authenticate_string
from .core import InvalidDigits
from .core import InvalidFormat
from .core import InvalidLength
from .core import BadAuthentication
from .core import InvalidValue

_ = TranslationStringFactory('rrn_kr')


def validate_rrn(node, cstruct):
    try:
        authenticate_string(cstruct)
    except InvalidLength:
        raise colander.Invalid(node, _('Invalid length'))
    except InvalidDigits:
        raise colander.Invalid(node, _('Invalid digits'))
    except InvalidFormat:
        raise colander.Invalid(node, _('Invalid format'))
    except BadAuthentication:
        raise colander.Invalid(node, _('Invalid value'))
    except InvalidValue:
        raise colander.Invalid(node, _('Invalid value'))
Esempio n. 15
0
"""I18n."""
from translationstring import TranslationStringFactory

_ = TranslationStringFactory("deform")
Esempio n. 16
0
from translationstring import TranslationStringFactory
_ = TranslationStringFactory("bfgtools")

Esempio n. 17
0
"""
use as import:
from nive.i18n import _
"""
from translationstring import TranslationStringFactory
_ = TranslationStringFactory('nive')

from pyramid.i18n import get_localizer
from pyramid.threadlocal import get_current_request


def translator(request=None):
    """
    a shortcut to create a translator to translate a term. calls pyramid `get_localizer(get_current_request())`
    to get the current language or creates a placeholder if in testing mode.
    
    the returned translator is a reference to the translate function.
    
    ::
        translate = translator()
        t = translate(term)

    """
    try:
        localizer = get_localizer(request or get_current_request())
    except:
        # for testing. just returns the term on translate().
        import helper
        localizer = helper.FakeLocalizer()
    return localizer.translate
Esempio n. 18
0
from translationstring import TranslationStringFactory
_ = TranslationStringFactory('messages')
from translationstring import TranslationStringFactory
_ = TranslationStringFactory('wiseguy')

from wiseguy.schema import StrictSchema  # API
from wiseguy.schema import Url  # API
from wiseguy.schema import WSGIApp  # API


class WSGIComponent(object):
    def __init__(self, schema, factory):
        self.schema = schema
        self.factory = factory
Esempio n. 20
0
from pyramid.i18n import default_locale_negotiator
from pyramid.settings import aslist
from translationstring import TranslationStringFactory


_ = TranslationStringFactory("getitfixed")


def locale_negotiator(request):
    locale_name = default_locale_negotiator(request)

    # available languages are not handled by pyramid itself
    if locale_name is None:
        available = aslist(request.registry.settings["pyramid.available_languages"])
        default = request.registry.settings["pyramid.default_locale_name"]
        locale_name = request.accept_language.lookup(available, default=default)

    return locale_name
Esempio n. 21
0
from pyramid.i18n import default_locale_negotiator
from pyramid.settings import aslist
from translationstring import TranslationStringFactory

_ = TranslationStringFactory('c2cgeoform_project')


def locale_negotiator(request):
    locale_name = default_locale_negotiator(request)

    # available languages are not handled by pyramid itself
    if locale_name is None:
        available = aslist(
            request.registry.settings['pyramid.available_languages'])
        locale_name = request.accept_language.best_match(available)

    return locale_name
Esempio n. 22
0
# For copyright and license terms, see COPYRIGHT.rst (top level of repository)
# Repository: https://github.com/C3S/collecting_society.portal.repertoire

from translationstring import TranslationStringFactory

translator = TranslationStringFactory('collecting_society_portal_repertoire')
Esempio n. 23
0
import logging
log = logging.getLogger('onegov.onboarding')  # noqa
log.addHandler(logging.NullHandler())  # noqa

from translationstring import TranslationStringFactory
_ = TranslationStringFactory('onegov.onboarding')  # noqa

from onegov.onboarding.app import OnboardingApp

__all__ = ['_', 'log', 'OnboardingApp']
Esempio n. 24
0
# For copyright and license terms, see COPYRIGHT.rst (top level of repository)
# Repository: https://github.com/C3S/collecting_society.portal.creative

from translationstring import TranslationStringFactory

translator = TranslationStringFactory('collecting_society_portal_creative')
Esempio n. 25
0
import logging

from translationstring import TranslationStringFactory

log = logging.getLogger('onegov.swissvotes')
log.addHandler(logging.NullHandler())
_ = TranslationStringFactory('onegov.swissvotes')

from onegov.swissvotes.app import SwissvotesApp  # noqa

__all__ = ('_', 'log', 'SwissvotesApp')
Esempio n. 26
0
# -*- coding: utf-8 -*-
"""Tools for user interface internationalization.

This package contains the translator factory "_" as well as the ZPT_RENDERER
factory for deform forms.
"""

from translationstring import TranslationStringFactory
from pyramid.i18n import (
    get_localizer, )
from pyramid.threadlocal import get_current_request
from pkg_resources import resource_filename
import deform

_ = TranslationStringFactory('c3smembership')


def translator(term):
    """
    Template translator.
    """
    return get_localizer(get_current_request()).translate(term)


MY_TEMPLATE_DIR = resource_filename('c3smembership', 'templates')
DEFORM_TEMPLATE_DIR = resource_filename('deform', 'templates')

ZPT_RENDERER = deform.ZPTRendererFactory(
    [
        MY_TEMPLATE_DIR,
        DEFORM_TEMPLATE_DIR,
Esempio n. 27
0
from pkg_resources import resource_filename
from pyramid.i18n import get_localizer
from pyramid.threadlocal import get_current_request
from pyramid.config import Configurator
from deform import Form, widget
from translationstring import TranslationStringFactory

_ = TranslationStringFactory('c2cgeoform')
""" Default search paths for the form templates.
"""
default_search_paths = (resource_filename('c2cgeoform', 'templates/widgets'),
                        resource_filename('deform', 'templates'))


def main(global_config, **settings):
    """
    This function returns a Pyramid WSGI application.
    In our case, this is only used for tests.
    """
    config = Configurator(settings=settings)
    return config.make_wsgi_app()


def includeme(config):
    """
    Function called when "c2cgeoform" is included in a project (with
    ``config.include('c2cgeoform')``).

    This function creates routes and views for c2cgeoform pages.
    """
    config.include('pyramid_chameleon')
Esempio n. 28
0
# coding=utf-8
from sqlalchemy import (Column, Integer, BigInteger, Text, Boolean, Date,
                        ForeignKey)
from sqlalchemy.orm import relationship
import geoalchemy2

import colander
import deform
from translationstring import TranslationStringFactory

from c2cgeoform.ext import colander_ext, deform_ext
from c2cgeoform.models import Base, FileData

_ = TranslationStringFactory('pully')


# FIXME a file upload memory store is not appropriate for production
# See http://docs.pylonsproject.org/projects/deform/en/latest/interfaces.html#deform.interfaces.FileUploadTempStore  # noqa
class FileUploadTempStore(dict):
    def preview_url(self, name):
        return None


_file_upload_temp_store = FileUploadTempStore()


class District(Base):
    __tablename__ = 'district'

    id = Column(Integer, primary_key=True)
    name = Column(Text, nullable=False)
Esempio n. 29
0
import c2cwsgiutils.pretty_json
from pkg_resources import resource_filename
from pyramid.config import Configurator
from pyramid.events import BeforeRender, NewRequest
from sqlalchemy import engine_from_config
from sqlalchemy.orm import configure_mappers, sessionmaker
from translationstring import TranslationStringFactory
import zope.sqlalchemy

from c2cgeoportal_admin.subscribers import add_localizer, add_renderer_globals

search_paths = (resource_filename(
    __name__, "templates/widgets"), ) + c2cgeoform.default_search_paths
c2cgeoform.default_search_paths = search_paths

_ = TranslationStringFactory("c2cgeoportal_admin")


def main(_, **settings):
    """
    This function returns a Pyramid WSGI application.
    """
    configuration.init(settings.get("app.cfg"))
    settings.update(configuration.get_config())

    config = Configurator(settings=settings)

    c2cwsgiutils.pretty_json.init(config)
    config.include("c2cgeoportal_admin")

    # Initialize the dev dbsession
Esempio n. 30
0
import logging
log = logging.getLogger('onegov.gazette')  # noqa
log.addHandler(logging.NullHandler())  # noqa

from translationstring import TranslationStringFactory
_ = TranslationStringFactory('onegov.gazette')  # noqa

from onegov.gazette.app import GazetteApp

__all__ = ['_', 'log', 'GazetteApp']