Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask g.user and before_request

I have a simple setup using flask-login shown below. When I hit the before_request, g.user is set correctly. I am also registering users correctly (as in they hit the db with the right email/pass). My problem is that between before_request and the page hit, g.user always becomes None. I think I'm missing something with session, but I can't tell what.

init:

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'

In the view/login.py file, I have the following.

views/login.py:

@app.lm.user_loader
def load_user(id):
    return models.user.user_with_id(id)

@app.before_request
def before_request():
    g.user = current_user
    print 'current_user: %s, g.user: %s, leaving bef_req' % (current_user, g.user)

@app.route('/login', methods=['GET', 'POST'])
def login():
    print 'in login, g.user: %s' % g.user
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))
    enter_form = app.forms.EnterForm()
    if enter_form.validate_on_submit():
        session['remember_me'] = True
        return app.models.user.try_register(enter_form.email.data,
                                            enter_form.password.data)
    return render_template('index.html', enter_form=enter_form, profiles=[])

views/index.py:

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    print 'in index, g.user: %s' % g.user
    if not g.user:
        return redirect(url_for('login'))
    return render_template('index.html')

models/user.py:

def try_login(email, password, remember_me):
    u = user_with_email(email)
    if u and authenticate(u, password):
        login_user(u, remember=remember_me)
    return app.views.index.go_to_index()

def try_register(email, password, role=ROLE_USER):
    if not user_with_email(email):
        add_user(password, role=role, email=email)
    return try_login(email, password)
like image 952
user592419 Avatar asked Oct 23 '13 02:10

user592419


1 Answers

Your try_login function takes remember_me as third parameter but in the snippet provided you do not set it when calling try_login in try_register. Maybe this is your problem. Note that remember_me should be a boolean.

And you also should put remember_me in the try_register call.

And last it's weird to call regsiter function in login function and try_login in register. The pattern is a bit messy :)

like image 164
Benoît Latinier Avatar answered Sep 28 '22 06:09

Benoît Latinier