示例#1
0
 def test_wash_dashed_language(self):
     """messages - washing dashed language code (fr-ca)"""
     if 'fr' not in cfg['CFG_SITE_LANGS']:
         self.assertEqual(messages.wash_language('fr-ca'),
                          cfg['CFG_SITE_LANG'])
     else:
         self.assertEqual(messages.wash_language('fr-ca'),
                          'fr')
示例#2
0
 def test_wash_dashed_language(self):
     """messages - washing dashed language code (fr-ca)"""
     if 'fr' not in cfg['CFG_SITE_LANGS']:
         self.assertEqual(messages.wash_language('fr-ca'),
                          cfg['CFG_SITE_LANG'])
     else:
         self.assertEqual(messages.wash_language('fr-ca'),
                          'fr')
def format_records(records, of='hb', ln=None, **ctx):
    """Return records using Jinja template."""
    from flask import request
    from invenio_base.i18n import wash_language
    from .registry import export_formats

    of = of.lower()
    jrec = request.values.get('jrec', ctx.get('jrec', 1), type=int)
    rg = request.values.get('rg', ctx.get('rg', 10), type=int)
    ln = ln or wash_language(request.values.get('ln', cfg['CFG_SITE_LANG']))
    ot = (request.values.get('ot', ctx.get('ot')) or '').split(',')

    if jrec > records:
        jrec = rg * (records // rg) + 1

    context = dict(
        of=of,
        jrec=jrec,
        rg=rg,
        ln=ln,
        ot=ot,
        facets={},
        time=time,
        records=records,
        export_formats=export_formats,
        format_record=format_record,
        **TEMPLATE_CONTEXT_FUNCTIONS_CACHE.template_context_functions)
    context.update(ctx)
    return render_template_to_string([
        'format/records/%s.tpl' % of,
        'format/records/%s.tpl' % of[0],
        'format/records/%s.tpl' %
        get_output_format_content_type(of).replace('/', '_')
    ], **context)
示例#4
0
def format_records(records, of='hb', ln=None, **ctx):
    """Return records using Jinja template."""
    from flask import request
    from invenio_base.i18n import wash_language
    from .registry import export_formats

    of = of.lower()
    jrec = request.values.get('jrec', ctx.get('jrec', 1), type=int)
    rg = request.values.get('rg', ctx.get('rg', 10), type=int)
    ln = ln or wash_language(request.values.get('ln', cfg['CFG_SITE_LANG']))
    ot = (request.values.get('ot', ctx.get('ot')) or '').split(',')

    if jrec > records:
        jrec = rg * (records // rg) + 1

    context = dict(
        of=of, jrec=jrec, rg=rg, ln=ln, ot=ot,
        facets={},
        time=time,
        records=records,
        export_formats=export_formats,
        format_record=format_record,
        **TEMPLATE_CONTEXT_FUNCTIONS_CACHE.template_context_functions
    )
    context.update(ctx)
    return render_template_to_string(
        ['format/records/%s.tpl' % of,
         'format/records/%s.tpl' % of[0],
         'format/records/%s.tpl' % get_output_format_content_type(of).
            replace('/', '_')],
        **context)
示例#5
0
def get_locale():
    """Compute the language needed to return the answer to the client."""
    from invenio_base.i18n import wash_language
    required_ln = None
    passed_ln = request.values.get('ln', type=str)
    if passed_ln:
        # If ln is specified explictly as a GET or POST argument
        # let's take it!
        required_ln = wash_language(passed_ln)
        if passed_ln != required_ln:
            # But only if it was a valid language
            required_ln = None
    if required_ln is None and 'ln' not in session:
        # If there is no language saved into the session...
        user_language = current_user.get('language')
        if user_language:
            # ... and the user is logged in, we try to take it from its
            # settings.
            required_ln = user_language
        else:
            # Otherwise we try to guess it from its request headers
            for value, quality in request.accept_languages:
                value = str(value)
                ln = wash_language(value)
                if ln == value or ln[:2] == value[:2]:
                    required_ln = ln
                    break
            else:
                # Too bad! We stick to the default :-)
                required_ln = current_app.config.get('CFG_SITE_LANG')
    elif required_ln is None:
        required_ln = session.get('ln')

    assert required_ln is not None

    if required_ln != session.get('ln',
                                  current_app.config.get('CFG_SITE_LANG')):
        session['ln'] = required_ln

    return required_ln
示例#6
0
def get_locale():
    """Compute the language needed to return the answer to the client."""
    from invenio_base.i18n import wash_language
    required_ln = None
    passed_ln = request.values.get('ln', type=str)
    if passed_ln:
        # If ln is specified explictly as a GET or POST argument
        # let's take it!
        required_ln = wash_language(passed_ln)
        if passed_ln != required_ln:
            # But only if it was a valid language
            required_ln = None
    if required_ln is None and 'ln' not in session:
        # If there is no language saved into the session...
        user_language = current_user.get('language')
        if user_language:
            # ... and the user is logged in, we try to take it from its
            # settings.
            required_ln = user_language
        else:
            # Otherwise we try to guess it from its request headers
            for value, quality in request.accept_languages:
                value = str(value)
                ln = wash_language(value)
                if ln == value or ln[:2] == value[:2]:
                    required_ln = ln
                    break
            else:
                # Too bad! We stick to the default :-)
                required_ln = current_app.config.get('CFG_SITE_LANG')
    elif required_ln is None:
        required_ln = session.get('ln')

    assert required_ln is not None

    if required_ln != session.get('ln',
                                  current_app.config.get('CFG_SITE_LANG')):
        session['ln'] = required_ln

    return required_ln
示例#7
0
 def test_wash_invalid_language(self):
     """messages - washing invalid language code"""
     self.assertEqual(messages.wash_language('python'),
                      cfg['CFG_SITE_LANG'])
示例#8
0
 def test_wash_invalid_language(self):
     """messages - washing invalid language code"""
     self.assertEqual(messages.wash_language('python'),
                      cfg['CFG_SITE_LANG'])
示例#9
0
def wash_urlargd(form, content):
    """
    Wash the complete form based on the specification in
    content. Content is a dictionary containing the field names as a
    key, and a tuple (type, default) as value.

    'type' can be list, str, invenio.legacy.wsgi.utils.StringField, int, tuple, or
    invenio.legacy.wsgi.utils.Field (for
    file uploads).

    The specification automatically includes the 'ln' field, which is
    common to all queries.

    Arguments that are not defined in 'content' are discarded.

    Note that in case {list,tuple} were asked for, we assume that
    {list,tuple} of strings is to be returned.  Therefore beware when
    you want to use wash_urlargd() for multiple file upload forms.

    @Return: argd dictionary that can be used for passing function
    parameters by keywords.
    """

    result = {}

    content['ln'] = (str, '')

    for k, (dst_type, default) in content.items():
        try:
            value = form[k]
        except KeyError:
            result[k] = default
            continue

        # FIXES problems with unicode arguments from Flask
        if isinstance(value, unicode):
            value = value.encode('utf-8')

        src_type = type(value)

        # First, handle the case where we want all the results. In
        # this case, we need to ensure all the elements are strings,
        # and not Field instances.
        if src_type in (list, tuple):
            if dst_type is list:
                result[k] = [str(x) for x in value]
                continue

            if dst_type is tuple:
                result[k] = tuple([str(x) for x in value])
                continue

            # in all the other cases, we are only interested in the
            # first value.
            value = value[0]

        # Maybe we already have what is expected? Then don't change
        # anything.
        if isinstance(value, dst_type):
            result[k] = value
            continue

        # Since we got here, 'value' is sure to be a single symbol,
        # not a list kind of structure anymore.
        if dst_type in (str, int):
            try:
                result[k] = dst_type(value)
            except Exception:
                result[k] = default

        elif dst_type is tuple:
            result[k] = (str(value), )

        elif dst_type is list:
            result[k] = [str(value)]

        else:
            raise ValueError(
                'cannot cast form value %s of type %r into type %r' %
                (value, src_type, dst_type))

    result['ln'] = wash_language(result['ln'])

    return result