Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading