Argparse URL type

Viewed 39

Let's have a simple argparser with one argument which shall represent URL.

from argparse import ArgumentParser

def my_url(arg):
"""
Some url validation

"""

parser = ArgumentParser(
    description="foobar"
)
parser.add_argument(
    "-u",
    "--url",
    type=my_url,
    help="foobar",
)

Is there ready up to take function to validate if argument is URL in order to omit my_url custom validation function?

1 Answers

You can use the urlparse function from urllib.parse & check if it was able to pull out all the required components from the URL:

from urllib.parse import urlparse


def my_url(arg):
    url = urlparse(arg)
    if all((url.scheme, url.netloc)):  # possibly other sections?
        return arg  # return url in case you need the parsed object
    raise ArgumentTypeError('Invalid URL')

Result:

parser.parse_args(['-u', 'http://locahost:2000'])  # pass
parser.parse_args(['-u', 'http/locahost:2000'])  # Invalid URL
parser.parse_args(['-u', 'thisisurl'])  # Invalid URL
Related