How to redirect to a URL in Python Flask?

Sometimes, we want to redirect to a URL in Python Flask.

In this article, we’ll look at how to redirect to a URL in Python Flask.

How to redirect to a URL in Python Flask?

To redirect to a URL in Python Flask, we can call the redirect function

For instance, we write

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

to call redirect in our hello view function with the URL and the response code for the redirect.

Conclusion

To redirect to a URL in Python Flask, we can call the redirect function