Skip to content
Myr

validation.py

This file

Path

examples/validation/validation.py

48 lines · 1.4 KiB · Python

Last changed by

`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489

History of this file

Take it

The walk stopped after 200 commits: lines older than 9ce34f2 point at it.

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 1–11why, one step back
1from urllib import parse as urlparse
23import click456def validate_count(ctx, param, value):7 if value < 0 or value % 2 != 0:8 raise click.BadParameter("Should be a positive, even integer.")9 return value1011

`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489

line 12why, one step back
12class URL(click.ParamType[urlparse.ParseResult]):

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 13–14why, one step back
13 name = "url"
14

`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489

line 15why, one step back
15 def convert(self, value, param, ctx) -> urlparse.ParseResult:

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 16–48why, one step back
16 if not isinstance(value, tuple):
17 value = urlparse.urlparse(value)18 if value.scheme not in ("http", "https"):19 self.fail(20 f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",21 param,22 ctx,23 )24 return value252627@click.command()28@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())33@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 """41 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 )46 click.echo(f"count: {count}")47 click.echo(f"foo: {foo}")48 click.echo(f"url: {url!r}")