Redirecting to URL in Flask - python

I'm trying to do the equivalent of Response.redirect as in C# - i.e.: redirect to a specific URL - how do I go about this?
Here is my code:
import os
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return 'Hello World!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)

You have to return a redirect:
import os
from flask import Flask,redirect
app = Flask(__name__)
#app.route('/')
def hello():
return redirect("http://www.example.com", code=302)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
See the documentation on flask docs. The default value for code is 302 so code=302 can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask import Flask, redirect, url_for
app = Flask(__name__)
#app.route('/')
def hello():
return redirect(url_for('foo'))
#app.route('/foo')
def foo():
return 'Hello Foo!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Take a look at the example in the documentation.

From the Flask API Documentation (v. 2.0.x):
flask.redirect(location, code=302, Response=None)
Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.6: The location can now be a unicode string that is
encoded using the iri_to_uri() function.
Parameters:
location – the location the response should redirect to.
code – the redirect status code. defaults to 302.
Response (class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.

I believe that this question deserves an updated. Just compare with other approaches.
Here's how you do redirection (3xx) from one url to another in Flask (0.12.2):
#!/usr/bin/env python
from flask import Flask, redirect
app = Flask(__name__)
#app.route("/")
def index():
return redirect('/you_were_redirected')
#app.route("/you_were_redirected")
def redirected():
return "You were redirected. Congrats :)!"
if __name__ == "__main__":
app.run(host="0.0.0.0",port=8000,debug=True)
For other official references, here.

flask.redirect(location, code=302)
Docs can be found here.

Flask includes the redirect function for redirecting to any url. Futhermore, you can abort a request early with an error code with abort:
from flask import abort, Flask, redirect, url_for
app = Flask(__name__)
#app.route('/')
def hello():
return redirect(url_for('hello'))
#app.route('/hello'):
def world:
abort(401)
By default a black and white error page is shown for each error code.
The redirect method takes by default the code 302. A list for http status codes here.

its pretty easy if u just want to redirect to a url without any status codes or anything like that u can simple say
from flask import Flask, redirect
app = Flask(__name__)
#app.route('/')
def redirect_to_link():
# return redirect method, NOTE: replace google.com with the link u want
return redirect('https://google.com')
here is the link to the Flask Docs for more explanation

For this you can simply use the redirect function that is included in flask
from flask import Flask, redirect
app = Flask(__name__)
#app.route('/')
def hello():
return redirect("https://www.exampleURL.com", code = 302)
if __name__ == "__main__":
app.run()
Another useful tip(as you're new to flask), is to add app.debug = True after initializing the flask object as the debugger output helps a lot while figuring out what's wrong.

There are two ways you can redirect to a URL in Flask.
You want to for example, redirect a user to another route after he or she login, etc.
You might also want to redirect a user to a route that expect some variable example: #app.route('/post/<string:post_id>')
Well, to implement flask redirect for case # 1, its simple, just do:
from flask import Flask,redirect,render_template,url_for
app = Flask(__name__)
#app.route('/login')
def login():
# if user credentials are valid, redirect to user dashboard
if login == True:
return redirect(url_for(app.dashboard))
else:
print("Login failed !, invalid credentials")
return render_template('login.html',title="Home Page")
#app.route('/dashboard')
def dashboard():
return render_template('dashboard.html',title="Dashboard")
To implement flask redirect for case #2, do the following
from flask import Flask,redirect,render_template,url_for
app = Flask(__name__)
#app.route('/home')
def home():
# do some logic, example get post id
if my_post_id:
# **Note:** post_id is the variable name in the open_post route
# We need to pass it as **post_id=my_post_id**
return redirect(url_for(app.open_post,post_id=my_post_id))
else:
print("Post you are looking for does not exist")
return render_template('index.html',title="Home Page")
#app.route('/post/<string:post_id>')
def open_post():
return render_template('readPost.html',title="Read Post")
Same thing can be done in view
Please Note: when redirecting always use the app.home or app.something.. (route or view function name) instead of using redirect("/home").
Reason is, if you modify the route example from "/home" to "/index/page" for some reason, then your code will break

You can use like this:
import os
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
# Redirect from here, replace your custom site url "www.google.com"
return redirect("https://www.google.com", code=200)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Here is the referenced link to this code.

How to Redirect Users / Requests in Flask
Throwing an Error inside of your API handler function will redirect your user to an error handler, which can handle redirection. Alternatively you can just call redirect like everyone else is saying, but this is another way of redirecting unauthorized users. To demonstrate what I mean, I've provided an example below.
In a case where Users should be Authorized
First lets assume you have a protected route of which you protected like this.
def handle_api_auth(func):
"""
**handle_api_auth**
wrapper to handle public api calls authentications
:param func: a function to be wrapped
:return: wrapped function
"""
#functools.wraps(func)
def auth_wrapper(*args, **kwargs):
api_key: Optional[str] = request.headers.get('x-api-key')
secret_token: Optional[str] = request.headers.get('x-secret-token')
domain: Optional[str] = request.base_url
if is_request_valid(api_key=api_key, secret=secret_token, domain=domain):
return func(*args, **kwargs)
# NOTE: throwing an Error Here will redirect your user to an error handler or alteratively you can just call redirect like everyone else is saying, but this is another way of redirecting unathorized users
message: str = "request not authorized"
raise UnAuthenticatedError(status=error_codes.un_auth_error_code, description=message)
return auth_wrapper
Definition of is_request_valid is as follows
#app_cache.cache.memoize(timeout=15 * 60, cache_none=False) # timeout equals fifteen minutes // 900 seconds
def is_request_valid(api_key: str, secret: str, domain: str) -> bool:
"""
**is_api_key_valid**
validates api keys on behalf of client api calls
:param api_key: str -> api_key to check
:param secret: str -> secret token
:param domain: str -> domain registered for the api_key and secret_token
:return: bool -> True if api_key is valid
"""
organization_id: str = config_instance.ORGANIZATION_ID
# NOTE: lets assumy api_keys_view.get_api_key will return the api keys from some database somewhere
response = api_keys_view.get_api_key(api_key=api_key, organization_id=organization_id)
response_data, status_code = response
response_dict = response_data.get_json()
if not response_dict.get('status'):
return False
api_instance: dict = response_dict.get('payload')
if not isinstance(api_instance, dict):
return False
domain: str = domain.lower().strip()
# NOTE accessing the keys this way will throw ValueError if keys are not available which is what we want
# Any Error which gets thrown Ridirects the Users from the path the user is on to an error handler.
is_secret_valid: bool = hmac.compare_digest(api_instance['secret_token'], secret)
is_domain_valid: bool = hmac.compare_digest(api_instance['domain'], domain)
_request_valid: bool = is_secret_valid and is_domain_valid
return not not api_instance.get('is_active') if _request_valid else False
Define your Error Handlers like this
from flask import Blueprint, jsonify, request, redirect
from werkzeug.exceptions Unauthorized
error_handler = BluePrint('error_handlers', __name__)
#error_handler.app_errorhandler(Unauthorized)
def handle_error(e : Unauthorized) -> tuple:
"""default unath handler"""
return jsonify(dict(message=e.description)), e.code if request.headers.get('content-type') == 'application/json' else redirect('/login')
handle other errors the same and note that in-case the request was
not a json the user gets redirected to a login page
if json the user gets sent an unathecated response then its
up to the front end to handle Unath Errors..

Related

redirect a POST to GET request

I'm trying to understand what is the best way a POST request can be redirected to a GET request.
for example -
POST /redirect HTTP/1.1
Host: www.example1.com
url=www.example2.com
and i've created the following flask to help me with that :
from flask import Flask,request, redirect
app = Flask(__name__)
#app.route('/redirect',methods=['POST'])
def redire():
url = request.form['url']
return redirect('https://www.example2.com', code=307)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888)
the "issue" in my case, is that the request that is being sent to
https://www.example2.com
is also a POST request which is not what i wanted.
Consider that I don't "care" about the body that needs to be sent to the
https://www.example2.com
endpoint, what is the best way to do so without any user intervention (meaning that I'm aiming for an auto redirect).
Note: I've tried to do it via PHP but I can't seem to figure it out.
Apologies if something is not clear.
In order to redirect a POST request to a GET request, you need to use code=303 because it requires the client to use the GET method to retrieve the requested resource.
#app.route('/redirect',methods=['POST'])
def redire():
url = request.form['url']
return redirect('https://www.example2.com', code=303)
the server
from flask import Flask, redirect
app = Flask(__name__)
#app.route('/redirect', methods=['POST'])
def redire():
return redirect('http://127.0.0.1:8888/get')
#app.route('/get', methods=['GET'])
def iam_get():
return {"code": "ok"}
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8888)
the client
import requests
data = requests.get("http://127.0.0.1:8888/get")
print(data.text)
data = requests.post("http://127.0.0.1:8888/redirect")
print(data.text)
the result as follows
{"code":"ok"}
{"code":"ok"}

Handling an url inside flask rule

I want my web to be able to handle URLs inside the rule,
just like:
http://127.0.0.1:5000/tiyee?url=https://tiyee.cn/iyu2
but getting an error:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I've tried with this code below but seems like it doesn't work
from flask import Flask, redirect
from tiyee import bypasser
app = Flask(__name__)
#app.route('/tiyee?url=<url>')
def _tiyee_redirect(url):
bypassed_json = bypasser(url)
return redirect(bypassed_json['bypassed_link'])
if __name__ == '__main__':
app.run(debug=True, port=5000)
Q: Is there a way to add URL inside the route rule?
example:
example.com/tiyee?url=https://tiyee.cn/iyu2 and get the https://tiyee.cn/iyu2
You are passing the url data in query. You will need to use request object to get the query value.
from flask import request
...
#app.route('/tiyee')
def _tiyee_redirect():
_url = request.args.get('url')
if _url is not None:
bypassed_json = bypasser(_url)
return redirect(bypassed_json['bypassed_link'])

why is this flask not showing standard message according to my code?

my rest service sits at http://127.0.0.1:5000, but when i launch it, it gives me 404:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
why is that? I want my server to show some status msg like 'service ready'.
The actual function that i will use is accessible and works, when i press 'http://127.0.0.1:5000/parser/tengrinews' and hit enter it outputs the msg i coded in the function in my flask app:
[
"parsing this website :",
"tengrinews"
]
the main code:
from flask import Flask
import requests
from datetime import datetime
from flask import jsonify
app = Flask(__name__)
#this is my std method i can't see
#app.route("/http://127.0.0.1:5000/", methods = ['GET'])
def main():
return jsonify('service is ready')
#app.route("/parser/<string:website>", methods = ['GET'])
def parse(website):
return jsonify("parsing this website :", website )
if __name__ == "__main__":
app.run(debug=True)
Change this line -
#app.route("/http://127.0.0.1:5000/", methods = ['GET'])
to
#app.route("/", methods = ['GET']).
Because you have to specify only the extended URL that will be used. The #app.route decorator handles the rest for us
Note* (Don't do this. For fun only) -
If you wish to continue to use #app.route("/http://127.0.0.1:5000/", methods = ['GET']) then access the endpoint with the url - http://localhost:5000/http://127.0.0.1:5000/. You will get the response as "service is ready"

How to send multiple parameters to route using flask?

I started learning Flask framework recently and made a short program to understand request/response cycle in flask.
My problem is that last method called calc doesn't work.
I send request as:
http://127.0.0.1/math/calculate/7/6
and I get error:
"Not Found:
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
Below is my flask app code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "<h1>Hello, World!</h1>"
#app.route('/user/<name>')
def user(name):
return '<h1>Hello, {0}!</h1>'.format(name)
#app.route('/math/calculate/<string:var1>/<int:var2>')
def calc(var1, var2):
return '<h1>Result: {0}!</h1>'.format(int(var1)+int(var2))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)
To access request arguments as described in your comment you can use the request library:
from flask import request
#app.route('/math/calculate/')
def calc():
var1 = request.args.get('var1',1,type=int)
var2 = request.args.get('var2',1,type=int)
return '<h1>Result: %s</h1>' % str(var1+var2)
The documentation for this method is documented here:
http://flask.pocoo.org/docs/1.0/api/#flask.Request.args
the prototype of the get method for extracting the value of keys from request.args is:
get(key, default=none, type=none)

Flask - function mapping is overwriting an existing endpoint function

I am trying to get the flask framework to work with Facebook. I'm doing this with flask_canvas. I followed the example for flask_canvas in the documentation (found here: http://flask-canvas.readthedocs.org/en/latest/) but I keep getting the following error:
AssertionError: View function mapping is overwriting an existing endpoint function: inner
If I comment out the method user(), it will run, but when that method is not commented out, I get the above error.
Any idea how to make it so I can have both the canvas() and user() methods without getting an AssertionError thrown?
import flask_canvas
from flask import Flask, session, redirect
app = Flask(__name__)
flask_canvas.install(app)
HOST = 'localhost'
PORT = 8000
#app.route('/')
def hello_world():
return 'Hello World!'
# route your canvas-specific page
#app.canvas_route('/app/', methods=['GET','POST'])
def canvas():
return 'hello, world'
#route page requiring user data
#app.canvas_route('/user/', methods=['GET','POST'])
def user(canvas_user):
return canvas_user.request('/me')
if __name__ == '__main__':
app.run(host = HOST, port = PORT, debug = True)
I had a similar issue, using a decorator without #wraps renames the function being decorated. See this for details http://flask.pocoo.org/docs/patterns/viewdecorators/
I encountered this problem, I think there may be two or more inner function in your app.
#app.route('/show1',methods=['GET','POST'])
def show():
return redirect(url)
#app.route('/show2',methods=['GET','POST'])
def show():
return redirect(url)
this will tell you an error:
AssertionError: View function mapping is overwriting an existing endpoint function: show

Categories

Resources