2

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.

nobinobiru
  • 792
  • 12
  • 28
  • To validate an URL you might want to look at using a regular expression. This will probably help: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python – petermlm Aug 24 '13 at 23:22

3 Answers3

6

Use urlparse (builtin module). Then, use the builtin flask redirection methods

>>> 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.

blakev
  • 4,154
  • 2
  • 32
  • 52
1

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
abdullahselek
  • 7,893
  • 3
  • 50
  • 40
-2

You can do something like this (not tested):

@app.route('/<path>')
def redirection(path):
    if path == '':    # your condition
        return redirect('redirect URL')
elyase
  • 39,479
  • 12
  • 112
  • 119