Reputation: 792
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.
Upvotes: 2
Views: 8299
Reputation: 8443
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
Upvotes: 1
Reputation: 4459
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.
Upvotes: 6
Reputation: 40973
You can do something like this (not tested):
@app.route('/<path>')
def redirection(path):
if path == '': # your condition
return redirect('redirect URL')
Upvotes: -2