validation.py
This file
Path
examples/validation/validation.py
52 lines · 1.5 KiB · Python
Last changed by
Merge branch '7.x'David Lordbefore adoption7239794
History of this fileTake it
The walk stopped after 200 commits: lines older than 2899795 point at it.
Merge branch 'her0e1c1-fix-secho'Markus Unterwaditzerbefore adoption2899795
line 1why, one step back1import clickMerge branch '7.x'David Lordbefore adoption7239794
line 2why, one step back2Merge branch 'her0e1c1-fix-secho'Markus Unterwaditzerbefore adoption2899795
line 3why, one step back3try:Fix invalid import in urlparse importWANG WENPEIbefore adoption3a6d3da
line 4why, one step back4 from urllib import parse as urlparseMerge branch 'her0e1c1-fix-secho'Markus Unterwaditzerbefore adoption2899795
lines 5–10why, one step back5except ImportError:6 import urlparse789def validate_count(ctx, param, value):10 if value < 0 or value % 2 != 0:Merge branch '7.x'David Lordbefore adoption7239794
line 11why, one step back11 raise click.BadParameter("Should be a positive, even integer.")Merge branch 'her0e1c1-fix-secho'Markus Unterwaditzerbefore adoption2899795
lines 12–15why, one step back12 return value131415class URL(click.ParamType):Merge branch '7.x'David Lordbefore adoption7239794
line 16why, one step back16 name = "url"Merge branch 'her0e1c1-fix-secho'Markus Unterwaditzerbefore adoption2899795
lines 17–20why, one step back1718 def convert(self, value, param, ctx):19 if not isinstance(value, tuple):20 value = urlparse.urlparse(value)Merge branch '7.x'David Lordbefore adoption7239794
lines 21–27why, one step back21 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 )Merge branch 'her0e1c1-fix-secho'Markus Unterwaditzerbefore adoption2899795
lines 28–31why, one step back28 return value293031@click.command()Merge branch '7.x'David Lordbefore adoption7239794
lines 32–36why, one step back32@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())Merge branch 'her0e1c1-fix-secho'Markus Unterwaditzerbefore adoption2899795
lines 37–44why, one step back37@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 """Merge branch '7.x'David Lordbefore adoption7239794
lines 45–52why, one step back45 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))