Question: I want to validate url before redirect it using Flask.

My abstract code is here...

```
@app.before_request
def before():
   if request.before_url == "http://127.0.0.0:8000":
       return redirect("http://127.0.0.1:5000")

```

Do you have any idea? 
Thanks in advance.

Answer: 
Use [urlparse (builtin module)](http://docs.python.org/2/library/urlparse.html). Then, use the builtin flask [redirection methods](http://flask.pocoo.org/docs/api/?highlight=redirect#flask.redirect)

```
>>> from urlparse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
>>> o   
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
        params='', query='', fragment='')
>>> o.scheme
'http'
>>> o.port
80
>>> o.geturl()
'http://www.cwi.nl:80/%7Eguido/Python.html'

```

You can then check for the parsed out port and reconstruct a url (using the same library) with the correct port or path. This will keep the integrity of your urls, instead of dealing with string manipulation.
You can use **urlparse** from **urllib** to parse the url. The function below which checks `scheme`, `netloc` and `path` variables which comes after parsing the url. Supports both Python 2 and 3.

```
try:
    # python 3
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

def url_validator(url):
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc, result.path])
    except:
        return False

```