validation.py
This file
Path
examples/validation/validation.py
52 lines · 1.5 KiB · Python
Last changed by
apply blackDavid Lordbefore adoption93ba3ba
History of this fileTake it
The walk stopped after 200 commits: lines older than 950463b point at it.
Fix typo (#817)scottbeldenbefore adoption950463b
line 1why, one step back1import clickapply reorder-python-importsDavid Lordbefore adoption488739d
line 2why, one step back2Fix typo (#817)scottbeldenbefore adoption950463b
line 3why, one step back3try:Fix invalid import in urlparse importWANG WENPEIbefore adoption3a6d3da
line 4why, one step back4 from urllib import parse as urlparseFix typo (#817)scottbeldenbefore adoption950463b
lines 5–10why, one step back5except ImportError:6 import urlparse789def validate_count(ctx, param, value):10 if value < 0 or value % 2 != 0:apply blackDavid Lordbefore adoption93ba3ba
line 11why, one step back11 raise click.BadParameter("Should be a positive, even integer.")Fix typo (#817)scottbeldenbefore adoption950463b
lines 12–15why, one step back12 return value131415class URL(click.ParamType):apply blackDavid Lordbefore adoption93ba3ba
line 16why, one step back16 name = "url"Fix typo (#817)scottbeldenbefore adoption950463b
lines 17–20why, one step back1718 def convert(self, value, param, ctx):19 if not isinstance(value, tuple):20 value = urlparse.urlparse(value)apply blackDavid Lordbefore adoption93ba3ba
lines 21–27why, one step back21 if value.scheme not in ("http", "https"):22 self.fail(23 "invalid URL scheme (%s). Only HTTP URLs are "24 "allowed" % value.scheme,25 param,26 ctx,27 )Fix typo (#817)scottbeldenbefore adoption950463b
lines 28–31why, one step back28 return value293031@click.command()apply blackDavid Lordbefore adoption93ba3ba
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())Fix typo (#817)scottbeldenbefore adoption950463b
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 """apply blackDavid Lordbefore adoption93ba3ba
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: %s" % count)51 click.echo("foo: %s" % foo)52 click.echo("url: %s" % repr(url))