Skip to content
Myr

Added validation example to docs.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 1407ecb · Browse files · 4 files+73 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+73 added−0 removed

  • other:+73 added−0 removed

4 files+73 added−0 removed

modified:docs/quickstart.rst+2 added
28 unmodified lines
29* ``repo``: `Git/hg like command line interface30 <https://github.com/mitsuhiko/click/tree/master/examples/repo>`_31* ``complex``: `Complex example with plugin loading32 <https://github.com/mitsuhiko/click/tree/master/examples/complex>`_33* ``validation``: `Custom parameter validation example34 <https://github.com/mitsuhiko/click/tree/master/examples/validation>`_3536Basic Concepts37--------------38
117 unmodified lines
added:examples/validation/README+12 added
1$ validation_23 validation is a simple example of an application that4 performs custom validation of parameters in different5 ways.67 This example requires Click 2.0 or higher.89Usage:1011 $ pip install --editable .12 $ validation --help
added:examples/validation/setup.py+15 added
1from setuptools import setup23setup(4 name='click-example-validation',5 version='1.0',6 py_modules=['validation'],7 include_package_data=True,8 install_requires=[9 'Click',10 ],11 entry_points='''12 [console_scripts]13 validation=validation:cli14 ''',15)
added:examples/validation/validation.py+44 added
1import click2try:3 from urllib import parser as urlparse4except ImportError:5 import urlparse678def validate_count(ctx, 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))