Skip to content
Myr

validation.py

This file

Path

examples/validation/validation.py

44 lines · 1.4 KiB · Python

Last changed by

Not known.

History of this file

Take it

1import click2try:3    from urllib import parser as urlparse4except ImportError:5    import urlparse678def validate_count(ctx, param, value):9    if value < 0 or value % 2 != 0:10        raise click.BadParameter('Should be a positive, even integer.')11    return value121314class URL(click.ParamType):15    name = 'url'1617    def convert(self, value, param, ctx):18        if not isinstance(value, tuple):19            value = urlparse.urlparse(value)20            if value.scheme not in ('http', 'https'):21                self.fail('invalid URL scheme (%s).  Only HTTP URLs are '22                          'allowed' % value.scheme, param, ctx)23        return value242526@click.command()27@click.option('--count', default=2, callback=validate_count,28              help='A positive even number.')29@click.option('--foo', help='A mysterious parameter.')30@click.option('--url', help='A URL', type=URL())31@click.version_option()32def cli(count, foo, url):33    """Validation.3435    This example validates parameters in different ways.  It does it36    through callbacks, through a custom type as well as by validating37    manually in the function.38    """39    if foo is not None and foo != 'wat':40        raise click.BadParameter('If a value is provided it needs to be the '41                                 'value "wat".', param_hint=['--foo'])42    click.echo('count: %s' % count)43    click.echo('foo: %s' % foo)44    click.echo('url: %s' % repr(url))