Flask框架 之Flask-login用户登录

文档:https://flask-login.readthedocs.io/en/latest/

安装:

pip install flask-login

一、效果图

 

 

二、示例代码

from flask import Flask, render_template, url_for, redirect, flash
from flask_login import LoginManager, login_required, UserMixin, login_user, logout_user, current_user
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired

app = Flask(__name__)

db = SQLAlchemy(app)

# 实例化登录管理对象
login_manager = LoginManager()
# 初始化应用
login_manager.init_app(app)
# 设置用户登录视图函数,即验证失败时要跳转的页面,这里设置为登录页
login_manager.login_view = "login"
login_manager.session_protection = "strong"

''' 数据库模型'''
class User(db.Model, UserMixin):
    __tablename__ = "user"

    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(32), nullable = False)
    password = db.Column(db.String(32))

'''表单模型'''
class LoginForm(FlaskForm):
    username = StringField(label="用户名", validators=[DataRequired("请输入用户名")])
    password = PasswordField(label="密码", validators=[DataRequired("请输入密码")])
    submit = SubmitField(label="登录")

''' 每访问一次,执行一次该函数 '''
@login_manager.user_loader
def load_user(user_id):
    # print("user_id=" + str(user_id))
    return User.query.filter_by(id=user_id).first()

@app.route('/')
@login_required
def index():
    # print(current_user)
    return render_template("user/index.html")

@app.route("/users")
@login_required
def users():
    users = User.query.order_by(desc("id")).all()
    return render_template("user/users.html", users = users)

@app.route("/login", methods=["POST", "GET"])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        # 1.从数据库查找用户
        user = User.query.filter_by(username=username).first()
        print(user)
        if user is not None:
            # 2.验证密码
            if user.password == password:
                # 3.登录
                login_user(user)
                return redirect(url_for('index'))
            else:
                flash("密码不正确")
        else:
            flash("用户名不正确")
    return render_template("user/login2.html", form=form)

@app.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

'''初始化数据'''
def init_data():
    u1 = User(username="yy", password="123456")
    u2 = User(username="admin", password="654321")

    db.session.add_all([u1, u2])
    db.session.commit()

if __name__ == '__main__':
    app.debug = True
    app.secret_key = "Yang"

    app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://test01:123456@127.0.0.1:3306/test01"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

    db.drop_all()
    db.create_all()
    # 初始化数据
    init_data()

    app.run()    

login.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
</head>

<body>
    <form action="{{url_for('login')}}" method="post" novalidate>
        {{form.csrf_token}}

        {{form.username.label}}
        <p>{{form.username}}</p>
        {% for msg in form.username.errors%}
        <p>{{msg}}</p>
        {% endfor%}

        {{form.password.label}}
        <p>{{form.password}}</p>
        {% for msg in form.password.errors%}
        <p>{{msg}}</p>
        {% endfor%}

        {{form.submit}}

        {% for message in get_flashed_messages() %}
        <div class=flash>{{ message }}</div>
        {% endfor %}
    </form>
</body>

</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    您好,{{ current_user.username }} <a href="{{url_for('logout')}}">退出登录</a> <a href="{{url_for('users')}}">用户列表</a>
</body>
</html>

 

posted @ 2023-03-31 16:10  样子2018  阅读(265)  评论(0编辑  收藏  举报