Python Flask: How to implement multiple URL redirects in bulk?

Question:

I am aware of Flask’s redirect(<URL>) function that I can use inside routes.

But I have dozens of URLs that I need to redirect to a different website. I was wondering if there is a way I can implement redirects without writing multiple redirect(<URL>) statements across many blueprints and routes.

I was wondering if I could just supply Flask with my redirect mapping data in bulk. e.g.

www.example.com/example-1 => subdomain.example.com/example-1
www.example.com/example-2 => subdomain.example.com/example-2
www.example.com/example-3 => subdomain.example.com/example-3
Asked By: Howard S

||

Answers:

Yes, you can do redirects with dictionaries or a list of tuples to hold them.

For example:

from flask import Flask, redirect

app = Flask(__name__)

# Define a dictionary of redirect mappings
redirects = {
    "/example-1": "http://subdomain.example.com/example-1",
    "/example-2": "http://subdomain.example.com/example-2",
    "/example-3": "http://subdomain.example.com/example-3"
}

# Register a route to handle all the redirects
@app.route('/<path:path>')
def redirect_to_new_url(path):
    if path in redirects:
        new_url = redirects[path]
        return redirect(new_url, code=302)
    else:
        return "Page not found", 404

if __name__ == '__main__':
    app.run(debug=True)
Answered By: Hack-R
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.