Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Build a Social Network with Flask Takin' Names Login View

Robust Tran
Robust Tran
2,802 Points

Login_user not working without set session?

I add the '@login_required' to the home page and it redirect users to login page successfully, however when it came to login and redirect back to home page, it did not work as I expected. But if I save the user's id to session, it will works. Like so " session['user_id] = user.id " in sign_in function?

here my view

#! /usr/bin/env python

from models import *
from forms import *
from flask import Flask
from flask import g, url_for, render_template, redirect, flash, request, session
from flask_bcrypt import check_password_hash
from flask_login import LoginManager, login_user, logout_user, login_required


DEBUG = True
HOST = '0.0.0.0'
PORT = 8000


app = Flask(__name__)
app.secret_key = 'fgjdhf@897^*jdsf&^hdsjfh2si(*jddsk'
login_mgr = LoginManager()
login_mgr.init_app(app)
login_mgr.login_view = 'sign_in'

@login_mgr.user_loader
def load_user(userid):
    try:
        return User.get(User.id == userid)
    except models.DoseNotExist:
        return None


@app.before_request
def before_request():
    """ Before the request action """
    g.db = models.DATABASE
    try:
        g.db.connect()
    except OperationalError:
        pass


@app.after_request
def after_request(response):
    """ After the request """
    try:
        g.db.close()
        return response
    except Exception as e:
        pass


@app.route('/sign-in', methods=['GET', 'POST'])
def sign_in():
    form = SignInForm()
    if form.validate_on_submit():
        try:
            user = User.get(User.email == form.email.data)
        except User.DoesNotExist:
            flash("Email or password is incorrect", 'error')
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                # Adding this line will make it works
                # session['user_id'] = user.id
                flash("You've been logged in!", "success")
                return redirect(url_for('index'))
            else:
                flash("Email or password is incorrect", 'error')
    return render_template('sign_in.html', form=form)


@app.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
    form = RegisterForm()
    if form.validate_on_submit():
        User.new(username=form.username.data, password=form.password.data, email=form.email.data)
        return redirect(url_for('index'))
    return render_template('sign_up.html', form=form)

@app.route('/sign-out')
@login_required
def sign_out():
    logout_user()
    return redirect(url_for('index'))

@app.route('/')
@login_required
def index():
    return "Hello"

if __name__ == '__main__':
    import models
    models.initialize()
    try:
        models.User.new(**{
            'username': 'Robust',
            'email':    'robust@gmail.com',
            'password': '123456',
        })
    except Exception as e:
        pass
    app.run(debug=DEBUG, port=PORT, host=HOST)

and my model.py

from peewee import *
from flask_bcrypt import generate_password_hash
from flask_login import UserMixin
import datetime


DATABASE = SqliteDatabase("social.db")

class User(UserMixin, Model):
    username =  CharField(unique=True)
    email =     CharField(unique=True)
    password =  CharField(max_length=255)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin =  BooleanField(default=False)
    is_active = BooleanField(default=False)

    class Meta(object):
        database = DATABASE
        order_by = ('-joined_at',)

    @classmethod
    def new(cls, **data):
        _password = generate_password_hash(data['password'])
        return cls.create(username=data['username'], email=data['email'], password=_password)

    def get_posts(self):
        return Post.select().where(Post.user == self)

    def get_stream(self):
        return Post.select().where(Post.user == self)


class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(rel_model=User, related_name='posts')

    class Meta(object):
        database = DATABASE
        order_by = ('-timestamp',)


def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User], safe=True)
    DATABASE.close()

Thanks you!!!