Home > Net >  Python-Flask render_template for user in session
Python-Flask render_template for user in session

Time:07-12

I've made a successfull login to a html page (lets call it page1). Now I need to allow access to a second page (page2) only if the user has previously done the login. I think I need an IF to specify to which page the user is attempting to go: page1 or page2.

This is what I got:

@app.route('/user')
def user():  
    if "user" in session:
        user = session["user"]
        return render_template("page1.html")
    else:
        return redirect(url_for("login"))

This following is wrong, I need that IF:

def user():  
    if "user" in session:
        user = session["user"]
        if ... : # user attempting to go to page 1
            return render_template("page1.html")
        else:
            return render_template("page2.html")
    else:
        return redirect(url_for("login"))

Thanks to all

Edited, to share the login method:

@app.route('/login', methods = ["GET","POST"])  
def login():
    error = None;  
    if request.method == "POST":
        user = request.form["email"]
        with open("users.txt", "r") as file:
            file_reader = csv.reader(file)
            for row in file_reader:
                if row[0] == request.form['email']:
                    user_found = [row[0],row[1]]
                    if user_found[1] != request.form['pass']:
                        error = "wrong pass"
                        break
                    else:  
                        flash("logged in")
                        session["user"]= user
                        return redirect(url_for('user'))
                else:
                    error = "user not found"
    else:
        if "user" in session:
            return redirect(url_for("user"))     
    return render_template('login.html',error=error)

CodePudding user response:

a better way to do this is to use flask-login. Views that require your users to be logged in can be decorated with the login_required decorator:

after installing flask-login, put the following in your main file or init.py

...
app = Flask(__name__)                       # constructs the Flask app

app.config.from_object('app.config.Config') # injects the configuration

db = SQLAlchemy  (app) # flask-sqlalchemy   # connects to SQLite DB

lm = LoginManager(   )                      # flask-loginmanager
lm.init_app(app)                            # init the login manager

then create your user model and inherit from user_mixin that provides default implementations for the methods that Flask-Login expects

class User(db.model, user_mixin):

then define the user loader

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

in your login route, after checking the username and password (enc) add the following to login the user:

login_user(user)

now you can decorate your protected views with login_required

@app.route("/page2")
@login_required
def page2():
    return render_template("page2.html")

@app.route("/page3")
@login_required
def page3():
    return render_template("page3.html")

CodePudding user response:

You can implement a wrapper function to check if a user is logged in. In that function utilize the global g variable.

from flask import g
from functools import wraps

def login_required(f):

    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not "user" in session:
            return redirect(url_for('login'))
        g.user = session["user"]
        return f(**args, **kwargs)

    return login_required


@app.route('/user')
@login_required
def user():
    return render_template("page1.html")

For a full example take a look at the View Decorators portion of the Flask documentation

  • Related