如何保持用户参与会话

时间:2019-07-03 09:00:16

标签: python flask

user=users.query.filter(db.and_(users.username ==  request.form['username'] ,users.password==request.form['password'])).first()

我已经尝试过

app.config['user'] = user and session['user']=user

,但不起作用

1 个答案:

答案 0 :(得分:0)

这里的方法存在一些明显的问题。确保首先阅读有关处理会话的Flask文档,这为您提供了一个非常不错的示例:

http://flask.pocoo.org/docs/1.0/quickstart/#sessions

from flask import Flask, session, redirect, url_for, escape, request
from werkzeug.security import check_password_hash

app = Flask(__name__)

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

def get_session_user():
    if 'username' not in session:
        return None
    username = session['username']
    # fetch the user from database somehow
    user = db.get_user_by_username(username)
    return user

def verify_password(hashed: str, password: str) -> bool:
    return check_password_hash(hashed, password)

@app.route('/')
def index():
    user = get_session_user()
    if user:
        return f'You are logged in as {user.username}'
    return f'Please <a href="/login">login</a>'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = db.get_user_by_username(username)

        if not user:
            return 'No such user'

        # hopefully you're storing hashed passwords in DB
        # you need to check if the credentials matches what's stored in DB
        if not verify_password(user.hashed_password, password):
            return 'Invalid credentials'

        session['username'] = user.username
        return redirect('/')

    return '''
        <form method="post">
            <input name='username' placeholder='username'>
            <input type='password' name='password' placeholder='password'>
            <button>Login</button>
        </form>
    '''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect('/')