Skip to content
Myr

validation.py

This file

Path

examples/validation/validation.py

52 lines · 1.5 KiB · Python

Last changed by

Merge pull request #1490 from pallets/styleDavid Lordbefore adoption38ba2e6

History of this file

Take it

1import click23try:4    from urllib import parse as urlparse5except ImportError:6    import urlparse789def validate_count(ctx, param, value):10    if value < 0 or value % 2 != 0:11        raise click.BadParameter("Should be a positive, even integer.")12    return value131415class URL(click.ParamType):16    name = "url"1718    def convert(self, value, param, ctx):19        if not isinstance(value, tuple):20            value = urlparse.urlparse(value)21            if value.scheme not in ("http", "https"):22                self.fail(23                    "invalid URL scheme ({}).  Only HTTP URLs are"24                    " allowed".format(value.scheme),25                    param,26                    ctx,27                )28        return value293031@click.command()32@click.option(33    "--count", default=2, callback=validate_count, help="A positive even number."34)35@click.option("--foo", help="A mysterious parameter.")36@click.option("--url", help="A URL", type=URL())37@click.version_option()38def cli(count, foo, url):39    """Validation.4041    This example validates parameters in different ways.  It does it42    through callbacks, through a custom type as well as by validating43    manually in the function.44    """45    if foo is not None and foo != "wat":46        raise click.BadParameter(47            'If a value is provided it needs to be the value "wat".',48            param_hint=["--foo"],49        )50    click.echo("count: {}".format(count))51    click.echo("foo: {}".format(foo))52    click.echo("url: {!r}".format(url))