Beispiel #1
0
def to_string(val):
    '''Decode string to string

    to_string :: String -> Result e String

    >>> from pydecoder.primitives import to_string

    Retrun result with decoded string

    >>> to_string('Foo Bar Baz')
    Result(status='Ok', value='Foo Bar Baz')

    if value isn't string returns error.

    >>> to_string(1234)
    Result(status='Error', value="'1234' isn't string.")
    '''
    if val is None:
        return error(u'Can\'t be null')

    if not isinstance(val, string_types):
        return error(u'\'{0!r}\' isn\'t string.'.format(val))

    return ok(val) if isinstance(val, text_type) else ok(
        text_type(val, 'utf-8'))
Beispiel #2
0
def to_bool(val):
    '''Decode string/value to boolean'''
    if isinstance(val, string_types):  # pylint: disable=no-else-return
        lowered_string = val.lower()
        if lowered_string == 'true':  # pylint: disable=no-else-return
            return ok(True)
        elif lowered_string == 'false':
            return ok(False)
        else:
            return error(u('String %s is invalid boolean value.' % val))
    elif isinstance(val, bool):
        return ok(val)
    else:
        return error(u('Value can\'t be decoded'))
Beispiel #3
0
def array(factory, vals):
    '''Decode string/value as list

    array :: (a -> Result e b) -> List a -> Result e (List b)

    >>> from pydecoder.primitives import to_int
    >>> array(to_int, [1, 2, 3])
    Result(status='Ok', value=[1, 2, 3])

    >>> array(to_int, None)
    Result(status='Error', value="'None' isn't list or tuple.")
    '''
    if not isinstance(vals, (list, tuple)):
        return error(u('\'{}\' isn\'t list or tuple.').format(vals))

    result = []

    for val in vals:
        rv = factory(val)

        if is_error(rv):
            return rv

        result.append(value(rv))

    return ok(result)
Beispiel #4
0
def getter(json, keys):  # pylint: disable=redefined-outer-name
    '''Get data from json'''

    try:
        return ok(get_in(_to_key_list(keys), json, no_default=True))
    except KeyError:
        return error(
            u'Value is empty or path/key {0!r} not found...'.format(keys))
Beispiel #5
0
def _time_traveled(data):
    return ok(data) if data['iat'] <= _now() else error(
        'Token traveled through time.')
Beispiel #6
0
def _expired(data):
    return ok(data) if data['exp'] >= _now() else error('Token expired.')
Beispiel #7
0
def getter(tree, key):
    '''Get data from tree'''
    return ok(map(lambda elm: elm.text, tree.iterfind(key)))
Beispiel #8
0
def to_int(val):
    '''Decode string/value to int'''
    try:
        return ok(int(val))
    except (TypeError, ValueError) as err:
        return error(text_type(err))
Beispiel #9
0
def null(val):
    '''Decode string/value to None'''
    if val is not None and val.lower() not in ('none', 'null'):
        return error(u('Value can\'t be decoded'))
    return ok(None)
Beispiel #10
0
 def dec(val):
     return ok(val - 1)
Beispiel #11
0
 def inc(val):
     return ok(val + 1)
Beispiel #12
0
def pipe(funcs, val):
    '''Pass value trough funcs

    pipe: List (value -> Result a) -> value -> Result a
    '''
    return reduce(lambda acc, item: andthen(item, acc), funcs, ok(val))