Flask - Redirect all routes of a particular Blueprint to external site

Viewed 246

i have a requirement where i want all routes of a particular blueprint be redirected to a external webpage.

For the below example i would want '/Store', '/Store/home', '/Store/products' be redirected to lets say 'google.com'. in actuall scenario there could be multiple routes mapped to a single blueprint i would want the other blueprint '/Online' untouched.

The use case here is that these modules(routes of blueprint1) have been moved to a different domain and i would want users to be redirected if they visit any of the url with the prefix 'Store'

Does anyone know of any function/workaround which can be used to achieve this?

from flask import Flask
from flask import Blueprint

app = Flask(__name__)
blueprint1 = Blueprint('example_blueprint', __name__)
blueprint2 = Blueprint('example_blueprint2', __name__)

@app.route('/')
def index():
    return "this is from root"

@blueprint1.route('/')
def index_b1():
    return "This is default route of blue print1"

@blueprint1.route('/home')
def index_b2():
    return "This is homepage of blue print"

@blueprint1.route('/products')
def index_b3():
    return "This is productpage of blue print"

@blueprint2.route('/')
def index_o1():
    return "This is default route of blue print 2"

app.register_blueprint(blueprint1,url_prefix='/Store')
app.register_blueprint(blueprint2,url_prefix='/Online')

if __name__ == "__main__":
    app.run(debug=True)
1 Answers

Use after_request (or before_request)

@blueprint1.after_request
def after_request_func(response):
    return redirect('https://www.pythonkitchen.com')

@blueprint2.after_request
def after_request_func(response):
    return redirect('https://www.pythonkitchen.com')

Related