validation.py
This file
Path
examples/validation/validation.py
48 lines · 1.4 KiB · Python
Last changed by
Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
History of this fileTake it
The walk stopped after 200 commits: lines older than a438322 point at it.
Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 1–2why, one step back1from urllib import parse as urlparse2Merge branch '7.x'David Lordbefore adoptiona438322
line 3why, one step back3import clickMerge branch '7.x'David Lordbefore adoption7239794
line 4why, one step back4Merge branch '7.x'David Lordbefore adoptiona438322
lines 5–7why, one step back56def validate_count(ctx, param, value):7 if value < 0 or value % 2 != 0:Merge branch '7.x'David Lordbefore adoption7239794
line 8why, one step back8 raise click.BadParameter("Should be a positive, even integer.")Merge branch '7.x'David Lordbefore adoptiona438322
lines 9–12why, one step back9 return value101112class URL(click.ParamType):Merge branch '7.x'David Lordbefore adoption7239794
line 13why, one step back13 name = "url"Merge branch '7.x'David Lordbefore adoptiona438322
lines 14–17why, one step back1415 def convert(self, value, param, ctx):16 if not isinstance(value, tuple):17 value = urlparse.urlparse(value)Merge branch '7.x'David Lordbefore adoption7239794
lines 18–19why, one step back18 if value.scheme not in ("http", "https"):19 self.fail(Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 20why, one step back20 f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",Merge branch '7.x'David Lordbefore adoption7239794
lines 21–23why, one step back21 param,22 ctx,23 )Merge branch '7.x'David Lordbefore adoptiona438322
lines 24–27why, one step back24 return value252627@click.command()Merge branch '7.x'David Lordbefore adoption7239794
lines 28–32why, one step back28@click.option(29 "--count", default=2, callback=validate_count, help="A positive even number."30)31@click.option("--foo", help="A mysterious parameter.")32@click.option("--url", help="A URL", type=URL())Merge branch '7.x'David Lordbefore adoptiona438322
lines 33–40why, one step back33@click.version_option()34def cli(count, foo, url):35 """Validation.3637 This example validates parameters in different ways. It does it38 through callbacks, through a custom type as well as by validating39 manually in the function.40 """Merge branch '7.x'David Lordbefore adoption7239794
lines 41–45why, one step back41 if foo is not None and foo != "wat":42 raise click.BadParameter(43 'If a value is provided it needs to be the value "wat".',44 param_hint=["--foo"],45 )Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 46–48why, one step back46 click.echo(f"count: {count}")47 click.echo(f"foo: {foo}")48 click.echo(f"url: {url!r}")