Skip to content
Myr

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 file

Take 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 back
1from urllib import parse as urlparse
2

Merge branch '7.x'David Lordbefore adoptiona438322

line 3why, one step back
3import click

Merge branch '7.x'David Lordbefore adoption7239794

line 4why, one step back
4

Merge branch '7.x'David Lordbefore adoptiona438322

lines 5–7why, one step back
5
6def validate_count(ctx, param, value):7 if value < 0 or value % 2 != 0:

Merge branch '7.x'David Lordbefore adoption7239794

line 8why, one step back
8 raise click.BadParameter("Should be a positive, even integer.")

Merge branch '7.x'David Lordbefore adoptiona438322

lines 9–12why, one step back
9 return value
101112class URL(click.ParamType):

Merge branch '7.x'David Lordbefore adoption7239794

line 13why, one step back
13 name = "url"

Merge branch '7.x'David Lordbefore adoptiona438322

lines 14–17why, one step back
14
15 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 back
18 if value.scheme not in ("http", "https"):
19 self.fail(

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 20why, one step back
20 f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",

Merge branch '7.x'David Lordbefore adoption7239794

lines 21–23why, one step back
21 param,
22 ctx,23 )

Merge branch '7.x'David Lordbefore adoptiona438322

lines 24–27why, one step back
24 return value
252627@click.command()

Merge branch '7.x'David Lordbefore adoption7239794

lines 28–32why, one step back
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())

Merge branch '7.x'David Lordbefore adoptiona438322

lines 33–40why, one step back
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 """

Merge branch '7.x'David Lordbefore adoption7239794

lines 41–45why, one step back
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 )

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 46–48why, one step back
46 click.echo(f"count: {count}")
47 click.echo(f"foo: {foo}")48 click.echo(f"url: {url!r}")