Python trafaret.List() Examples

The following are 18 code examples of trafaret.List(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module trafaret , or try the search function .
Example #1
Source File: layout_utils.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def build_field(key, value, relations=None):
    extra = None
    name = key
    if isinstance(value, t.ToInt):
        v = "number"
    elif isinstance(value, (t.String, t.URL)):
        v = "string"
    elif isinstance(value, t.Email):
        v = "email"
    elif isinstance(value, t.ToFloat):
        v = "float"
    elif isinstance(value, t.Enum):
        v = "choice"
    elif isinstance(value, (t.Dict, t.List)):
        v = "json"
    elif isinstance(value, (t.Bool, t.StrBool)):
        v = "boolean"
    elif isinstance(value, DateTime):
        v = "datetime"
    else:
        v = "string"
    return name, v, extra 
Example #2
Source File: db_fixtures.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def document_schema():
    choices = ['a', 'b', 'c']
    schema = t.Dict({
        t.Key('_id'): MongoId,
        t.Key('title'): t.String(max_length=200),
        t.Key('category'): t.String(max_length=200),
        t.Key('body'): t.String,
        t.Key('views'): t.ToInt,
        t.Key('average_note'): t.ToFloat,
        # t.Key('pictures'): t.Dict({}).allow_extra('*'),
        t.Key('published_at'): DateTime,
        # t.Key('tags'): t.List(t.Int),
        t.Key('status'): t.Enum(*choices),
        t.Key('visible'): t.ToBool,
    })
    return schema 
Example #3
Source File: ql.py    From flask-graphql-example with MIT License 6 votes vote down vote up
def mutate(cls, _, info, __):
        logger.debug("agrs %s", info)
        post_schema = t.Dict({
            'title': t.String(min_length=2),
            'user_id': t.String(min_length=2),
            'content': t.String(min_length=2),
            t.Key('tags',
                  optional=True): t.List(t.String,
                                         min_length=1),
        })

        post_data = post_schema.check(info)
        user_id = post_data.pop('user_id')
        user = User.objects.get_or_404(id=user_id)
        post = Post(author=user, **post_data)
        post.save()
        return cls(post=construct(PostField, post)) 
Example #4
Source File: test_constructor.py    From trafaret with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_dict(self):
        tt = construct({
            'a': int,
            'b': [str],  # test List
            'c': (str, str, 'atom string'),  # test Tuple
            'f': float,  # test float
            't': Decimal,  # test Type
            t.Key('k'): int,  # test Key
        })
        assert tt({
            'a': 5,
            'b': [u'a'],
            'c': [u'v', u'w', 'atom string'],
            'f': 0.1,
            't': Decimal('100'),
            'k': 100,
        }) == {
                'a': 5,
                'b': ['a'],
                'c': (u'v', u'w', 'atom string'),
                'f': 0.1,
                't': Decimal('100'),
                'k': 100,
        } 
Example #5
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_list(self):
        res = extract_error(t.List(t.ToInt), 1)
        assert res == 'value is not a list'
        res = t.List(t.ToInt).check([1, 2, 3])
        assert res == [1, 2, 3]
        res = t.List(t.String).check([u"foo", u"bar", u"spam"])
        assert res == [u'foo', u'bar', u'spam']
        res = extract_error(t.List(t.ToInt), [1, 2, 1 + 3j])
        assert res == {2: 'value is not int'}
        res = t.List(t.ToInt, min_length=1).check([1, 2, 3])
        assert res == [1, 2, 3]
        res = extract_error(t.List(t.ToInt, min_length=1), [])
        assert res == 'list length is less than 1'
        res = t.List(t.ToInt, max_length=2).check([1, 2])
        assert res == [1, 2]
        res = extract_error(t.List(t.ToInt, max_length=2), [1, 2, 3])
        assert res == 'list length is greater than 2'
        res = extract_error(t.List(t.ToInt), ["a"])
        assert res == {0: "value can't be converted to int"} 
Example #6
Source File: test_trafaret.py    From pydantic with MIT License 5 votes vote down vote up
def __init__(self, allow_extra):
        self.schema = t.Dict({
            'id': t.Int(),
            'client_name': t.String(max_length=255),
            'sort_index': t.Float,
            # t.Key('client_email', optional=True): t.Or(t.Null | t.Email()),
            t.Key('client_phone', optional=True): t.Or(t.Null | t.String(max_length=255)),

            t.Key('location', optional=True): t.Or(t.Null | t.Dict({
                'latitude': t.Or(t.Float | t.Null),
                'longitude': t.Or(t.Float | t.Null),
            })),

            t.Key('contractor', optional=True): t.Or(t.Null | t.Int(gt=0)),
            t.Key('upstream_http_referrer', optional=True): t.Or(t.Null | t.String(max_length=1023)),
            t.Key('grecaptcha_response'): t.String(min_length=20, max_length=1000),

            t.Key('last_updated', optional=True): t.Or(t.Null | t.String >> parse),

            t.Key('skills', default=[]): t.List(t.Dict({
                'subject': t.String,
                'subject_id': t.Int,
                'category': t.String,
                'qual_level': t.String,
                'qual_level_id': t.Int,
                t.Key('qual_level_ranking', default=0): t.Float,
            })),
        })
        if allow_extra:
            self.schema.allow_extra('*') 
Example #7
Source File: vfolder.py    From backend.ai-manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
def list_shared_vfolders(request: web.Request, params: Any) -> web.Response:
    '''
    List shared vfolders.

    Not available for group vfolders.
    '''
    dbpool = request.app['dbpool']
    access_key = request['keypair']['access_key']
    target_vfid = params['vfolder_id']
    log.info('VFOLDER.LIST_SHARED_VFOLDERS (ak:{})', access_key)
    async with dbpool.acquire() as conn:
        j = (vfolder_permissions
             .join(vfolders, vfolders.c.id == vfolder_permissions.c.vfolder)
             .join(users, users.c.uuid == vfolder_permissions.c.user))
        query = (sa.select([vfolder_permissions,
                            vfolders.c.id, vfolders.c.name,
                            users.c.email])
                   .select_from(j)
                   .where((vfolders.c.user == request['user']['uuid'])))
        if target_vfid is not None:
            query = query.where(vfolders.c.id == target_vfid)
        result = await conn.execute(query)
        shared_list = await result.fetchall()
    shared_info = []
    for shared in shared_list:
        shared_info.append({
            'vfolder_id': str(shared.id),
            'vfolder_name': str(shared.name),
            'shared_by': request['user']['email'],
            'shared_to': {
                'uuid': str(shared.user),
                'email': shared.email,
            },
            'perm': shared.permission.value,
        })
    resp = {'shared': shared_info}
    return web.json_response(resp, status=200) 
Example #8
Source File: constructor.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def construct(arg):
    '''
    Shortcut syntax to define trafarets.

    - int, str, float and bool will return t.Int, t.String, t.Float and t.Bool
    - one element list will return t.List
    - tuple or list with several args will return t.Tuple
    - dict will return t.Dict. If key has '?' at the and it will be optional and '?' will be removed
    - any callable will be t.Call
    - otherwise it will be returned as is

    construct is recursive and will try construct all lists, tuples and dicts args
    '''
    if isinstance(arg, t.Trafaret):
        return arg
    elif isinstance(arg, tuple) or (isinstance(arg, list) and len(arg) > 1):
        return t.Tuple(*(construct(a) for a in arg))
    elif isinstance(arg, list):
        # if len(arg) == 1
        return t.List(construct(arg[0]))
    elif isinstance(arg, dict):
        return t.Dict({construct_key(key): construct(value) for key, value in arg.items()})
    elif isinstance(arg, str):
        return t.Atom(arg)
    elif isinstance(arg, type):
        if arg is int:
            return t.ToInt()
        elif arg is float:
            return t.ToFloat()
        elif arg is str:
            return t.String()
        elif arg is bool:
            return t.Bool()
        else:
            return t.Type(arg)
    elif callable(arg):
        return t.Call(arg)
    else:
        return arg 
Example #9
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_repr(self):
        res = t.Iterable(t.ToInt)
        assert repr(res) == '<List(<ToInt>)>'
        res = t.Iterable(t.Int, min_length=0, max_length=10)
        assert repr(res) == '<List(max_length=10 | <Int>)>'
        res = t.Iterable(t.Int, min_length=1, max_length=10)
        assert repr(res) == '<List(min_length=1, max_length=10 | <Int>)>' 
Example #10
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_list_repr(self):
        res = t.List(t.ToInt)
        assert repr(res) == '<List(<ToInt>)>'
        res = t.List(t.ToInt, min_length=1)
        assert repr(res) == '<List(min_length=1 | <ToInt>)>'
        res = t.List(t.ToInt, min_length=1, max_length=10)
        assert repr(res) == '<List(min_length=1, max_length=10 | <ToInt>)>'
        res = t.List[t.ToInt]
        assert repr(res) == '<List(<ToInt>)>'
        res = t.List[t.ToInt, 1:]
        assert repr(res) == '<List(min_length=1 | <ToInt>)>'
        res = t.List[:10, t.ToInt]
        assert repr(res) == '<List(max_length=10 | <ToInt>)>' 
Example #11
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_2_0_regression(self):
        t_request = t.Dict({
            t.Key('params', optional=True): t.Or(t.List(t.Any()), t.Mapping(t.AnyString(), t.Any())),
        })
        assert t_request.check({'params': {'aaa': 123}}) == {'params': {'aaa': 123}} 
Example #12
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_list_meta(self):
        with pytest.raises(RuntimeError) as exc_info:
            t.List[1:10]
        assert exc_info.value.args[0] == 'Trafaret is required for List initialization' 
Example #13
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_forward(self):
        node = t.Forward()
        res = extract_error(node, 'something')
        assert res == 'trafaret not set yet'
        node << t.Dict(name=t.String, children=t.List[node])
        assert node.check({"name": u"foo", "children": []}) == {'children': [], 'name': u'foo'}
        res = extract_error(node, {"name": u"foo", "children": [1]})
        assert res == {'children': {0: 'value is not a dict'}}
        res = node.check({"name": u"foo", "children": [{"name": u"bar", "children": []}]})
        assert res == {'children': [{'children': [], 'name': u'bar'}], 'name': u'foo'}

        with pytest.raises(RuntimeError):  # __rshift__ is not overridden
            node << t.Int() 
Example #14
Source File: test_context.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_forward(self):
        trafaret = t.Forward()
        trafaret << t.List(CONTEXT_TRAFARET)
        assert trafaret([123], context=123) == [123] 
Example #15
Source File: test_context.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_list(self):
        trafaret = t.List(CONTEXT_TRAFARET)
        assert trafaret([123], context=123) == [123] 
Example #16
Source File: test_async.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_forward():
    trafaret = t.Forward()
    trafaret << t.List(t.ToInt & check_int)
    res = await (trafaret.async_check(['5']))
    assert res == [5] 
Example #17
Source File: test_async.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_list():
    trafaret = t.List(t.ToInt & check_int)
    res = await (trafaret.async_check(['5']))
    assert res == [5]
    with pytest.raises(t.DataError) as res:
        await trafaret.async_check(['5qwe'])
    assert res.value.as_dict() == {0: "value can't be converted to int"} 
Example #18
Source File: sa_utils.py    From aiohttp_admin with Apache License 2.0 5 votes vote down vote up
def build_trafaret(sa_type, **kwargs):

    if isinstance(sa_type, sa.sql.sqltypes.Enum):
        trafaret = t.Enum(*sa_type.enums, **kwargs)

    # check for Text should be before String
    elif isinstance(sa_type, sa.sql.sqltypes.Text):
        trafaret = t.String(**kwargs)

    elif isinstance(sa_type, sa.sql.sqltypes.String):
        trafaret = t.String(max_length=sa_type.length, **kwargs)

    elif isinstance(sa_type, sa.sql.sqltypes.Integer):
        trafaret = t.ToInt(**kwargs)

    elif isinstance(sa_type, sa.sql.sqltypes.Float):
        trafaret = t.ToFloat(**kwargs)

    elif isinstance(sa_type, sa.sql.sqltypes.DateTime):
        trafaret = DateTime(**kwargs)  # RFC3339

    elif isinstance(sa_type, sa.sql.sqltypes.Date):
        trafaret = DateTime(**kwargs)  # RFC3339

    elif isinstance(sa_type, sa.sql.sqltypes.Boolean):
        trafaret = t.ToBool(**kwargs)

    # Add PG related JSON and ARRAY
    elif isinstance(sa_type, postgresql.JSON):
        trafaret = AnyDict | t.List(AnyDict)

    # Add PG related JSON and ARRAY
    elif isinstance(sa_type, postgresql.ARRAY):
        item_trafaret = build_trafaret(sa_type.item_type)
        trafaret = t.List(item_trafaret)

    else:
        type_ = str(sa_type)
        msg = 'Validator for type {} not implemented'.format(type_)
        raise NotImplementedError(msg)
    return trafaret