Skip to content
Myr

validation.py

This file

Path

examples/validation/validation.py

48 lines · 1.4 KiB · Python

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 0805f60 point at it.

Merge pull request #1793 from MLH-Fellowship/jupyter-windows-supportDavid Lordbefore adoption0805f60

lines 1–48why, 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 value101112class URL(click.ParamType):13 name = "url"1415 def convert(self, value, param, ctx):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}")