Archive
Posts Tagged ‘valid url’
[flask] validate a URL
August 23, 2015
Leave a comment
Problem
In a Flask application I wanted to verify if a user-given URL is valid.
Solution
I found a simple validator package for that called validators (see it on GitHub).
Sample usage:
$ pip install validators
$ python
>>> import validators
>>> url = "http://index.hu"
>>> validators.url(url)
True
>>> url = "http://index.h/"
>>> validators.url(url)
ValidationFailure(func=url, args={'value': 'http://index.h/', 'require_tld': True})
The ValidationFailure class implements the __bool__ method, so you can easily check if validation failed:
if not validators.url(url):
flash("Error: you must provide a valid URL!")
