'Redirect to another page in blueprints

Im looking for a way to redirect to another page while using flask blueprints

from flask import Blueprint, request, render_template, redirect, url_for
import json

user = Blueprint("user",__name__,template_folder='templates')


@user.route("/index")
def index():
    return render_template("index.html")

@user.route("/signup")
def signup():
    return render_template("signup.html")

@user.route("/login")
def login():
    return render_template("login.html")

from models.user_model import User
from app import db

@user.route('/saveuser/', methods=['GET'])
def saveuser():
    username = request.args["username"]
    emailid = request.args["email"]
    password = request.args["password"]
    try:
        u = User(str(username),str(emailid),password=str(password))
        db.session.add(u)
        db.session.commit()
    except Exception, excp:
        return excp
    # return redirect('/index')
    return render_template("index.html")

In saveuser() I want to redirect to index page if Im able to insert successfully



Solution 1:[1]

Use redirect and url_for:

return redirect(url_for('user.index'))

Solution 2:[2]

Use the following working example and adjust it to fit your needs:

from flask import Flask, Blueprint, render_template, redirect, url_for

user = Blueprint("user", __name__, template_folder='templates')


@user.route("/index")
def index():
    return render_template("index.html")


@user.route('/saveuser/', methods=['GET'])
def saveuser():
    # save your user here
    return redirect(url_for('user.index'))


app = Flask(__name__)

app.register_blueprint(user)


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Healy
Solution 2 ettanany