python-click/examples/validation/validation.py

49 lines
1.4 KiB
Python
Raw Normal View History

2021-10-10 03:31:57 +02:00
from urllib import parse as urlparse
2020-07-21 08:23:42 +02:00
2021-10-10 03:31:57 +02:00
import click
2014-10-16 20:40:34 +02:00
def validate_count(ctx, param, value):
if value < 0 or value % 2 != 0:
2020-07-21 08:23:42 +02:00
raise click.BadParameter("Should be a positive, even integer.")
2014-10-16 20:40:34 +02:00
return value
class URL(click.ParamType):
2020-07-21 08:23:42 +02:00
name = "url"
2014-10-16 20:40:34 +02:00
def convert(self, value, param, ctx):
if not isinstance(value, tuple):
value = urlparse.urlparse(value)
2020-07-21 08:23:42 +02:00
if value.scheme not in ("http", "https"):
self.fail(
2021-10-10 03:31:57 +02:00
f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",
2020-07-21 08:23:42 +02:00
param,
ctx,
)
2014-10-16 20:40:34 +02:00
return value
@click.command()
2020-07-21 08:23:42 +02:00
@click.option(
"--count", default=2, callback=validate_count, help="A positive even number."
)
@click.option("--foo", help="A mysterious parameter.")
@click.option("--url", help="A URL", type=URL())
2014-10-16 20:40:34 +02:00
@click.version_option()
def cli(count, foo, url):
"""Validation.
This example validates parameters in different ways. It does it
through callbacks, through a custom type as well as by validating
manually in the function.
"""
2020-07-21 08:23:42 +02:00
if foo is not None and foo != "wat":
raise click.BadParameter(
'If a value is provided it needs to be the value "wat".',
param_hint=["--foo"],
)
2021-10-10 03:31:57 +02:00
click.echo(f"count: {count}")
click.echo(f"foo: {foo}")
click.echo(f"url: {url!r}")