Python trafaret.Bool() Examples

The following are 10 code examples of trafaret.Bool(). 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: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_bool(self, check_value, result):
        res = t.Bool().check(check_value)
        assert res == result 
Example #3
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_extract_error(self):
        err = extract_error(t.Bool(), 1)
        assert err == 'value should be True or False' 
Example #4
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_repr(self):
        assert repr(t.Bool()) == '<Bool>' 
Example #5
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_repr(self):
        assert repr(t.Bool & t.Null) == '<And(<Bool>, <Null>)>' 
Example #6
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_extract_error(self):
        res = extract_error(t.ToBool(), 'aloha')
        assert res == "value can't be converted to Bool" 
Example #7
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_on_error_ensured_trafaret(self):
        trafaret = t.OnError(t.Bool, message='Changed message')
        res = trafaret(False)
        assert res is False 
Example #8
Source File: test_base.py    From trafaret with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_on_error_data_error(self):
        trafaret = t.OnError(t.Bool, message='Changed message')
        res = catch_error(trafaret, 'Trololo')
        assert res.as_dict() == 'Changed message' 
Example #9
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 #10
Source File: vfolder.py    From backend.ai-manager with GNU Lesser General Public License v3.0 4 votes vote down vote up
def download_with_token(request) -> web.StreamResponse:
    try:
        secret = request.app['config']['manager']['secret']
        token = request.query.get('token', '')
        params = jwt.decode(token, secret, algorithms=['HS256'])
    except jwt.PyJWTError:
        log.exception('jwt error while parsing "{}"', token)
        raise InvalidAPIParameters('Could not validate the download token.')

    iv = t.Dict({
        t.Key('file'): t.String,
        t.Key('host'): t.String,
        t.Key('id'): t.String,
        t.Key('exp'): t.Int,
        t.Key('archive', default=False): t.Bool | t.Null,
    })
    params = iv.check(params)
    fn = params['file']
    log.info('VFOLDER.DOWNLOAD_WITH_TOKEN (token:{}, path:{})', token, fn)
    dbpool = request.app['dbpool']
    async with dbpool.acquire() as conn:
        query = (sa.select([vfolders.c.unmanaged_path])
                   .select_from(vfolders)
                   .where(vfolders.c.id == params['id'])
                   .limit(1))
        unmanaged_path = await conn.scalar(query)
        if unmanaged_path:
            folder_path = Path(unmanaged_path)
        else:
            folder_path = (request.app['VFOLDER_MOUNT'] / params['host'] /
                           request.app['VFOLDER_FSPREFIX'] / params['id'])
    try:
        file_path = (folder_path / fn).resolve()
        file_path.relative_to(folder_path)
        if not file_path.exists():
            raise FileNotFoundError
    except (ValueError, FileNotFoundError):
        raise InvalidAPIParameters('The file is not found.')
    if not file_path.is_file():
        if params['archive']:
            # Download directory as an archive when archive param is set.
            return await download_directory_as_archive(request, file_path)
        else:
            raise InvalidAPIParameters('The file is not a regular file.')
    if request.method == 'HEAD':
        return web.Response(status=200, headers={
            hdrs.ACCEPT_RANGES: 'bytes',
            hdrs.CONTENT_LENGTH: str(file_path.stat().st_size),
        })
    ascii_filename = file_path.name.encode('ascii', errors='ignore').decode('ascii').replace('"', r'\"')
    encoded_filename = urllib.parse.quote(file_path.name, encoding='utf-8')
    return web.FileResponse(file_path, headers={
        hdrs.CONTENT_TYPE: "application/octet-stream",
        hdrs.CONTENT_DISPOSITION: " ".join([
            "attachment;"
            f"filename=\"{ascii_filename}\";",       # RFC-2616 sec2.2
            f"filename*=UTF-8''{encoded_filename}",  # RFC-5987
        ])
    })