validation.py
This file
Path
examples/validation/validation.py
44 lines · 1.4 KiB · Python
Last changed by
Fix invalid import in urlparse importWANG WENPEIbefore adoption3a6d3da
History of this fileTake it
The walk stopped after 200 commits: lines older than 2534940 point at it.
Added link to example github issue.Armin Ronacherbefore adoption2534940
lines 1–2why, one step back1import click2try:Fix invalid import in urlparse importWANG WENPEIbefore adoption3a6d3da
line 3why, one step back3 from urllib import parse as urlparseAdded link to example github issue.Armin Ronacherbefore adoption2534940
lines 4–44why, one step back4except 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))