Skip to content
Myr

validation.py

This file

Path

examples/validation/validation.py

44 lines · 1.4 KiB · Python

Last changed by

Changed parameter callback signature.Armin Ronacherbefore adoptionbda39db

History of this file

Take it

Added validation example to docs.Armin Ronacherbefore adoption438b945

lines 1–7why, one step back
1import click
2try:3 from urllib import parser as urlparse4except ImportError:5 import urlparse67

Changed parameter callback signature.Armin Ronacherbefore adoptionbda39db

line 8why, one step back
8def validate_count(ctx, param, value):

Added validation example to docs.Armin Ronacherbefore adoption438b945

lines 9–29why, one step back
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.')

Fixed the example i accidentally broke.Armin Ronacherbefore adoptionf5b2e39

line 30why, one step back
30@click.option('--url', help='A URL', type=URL())

Added validation example to docs.Armin Ronacherbefore adoption438b945

lines 31–44why, one step back
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))