Flask实现登录注册,以及用session实现状态保持

话不多说,直接上干货

先引用插件

from flask import Flask, render_template, session, request, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
import pymysql
import redis

再完成相关的配置

pymysql.install_as_MySQLdb()
# 初始化Session对象
f_session = Session()

app = Flask(__name__)
# 设置连接数据库的URL
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/xiangqin'
# 数据库和模型类同步修改
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 查询是会显示原始SQL语句
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

app.config['SECRET_KEY'] = 'laowangaigebi'  # 加密的密钥
app.config['SESSION_USE_SIGNER'] = True  # 是否对发送到浏览器上session的cookie值进行加密
app.config['SESSION_TYPE'] = 'redis'  # session类型为redis
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前缀
app.config['PERMANENT_SESSION_LIFETIME'] = 7200  # 失效时间 秒
app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379', db=4)  # redis数据库连接

# 绑定flask的对象
f_session.init_app(app)

app.config['SECRET_KEY'] = 'xiaohuaxiaohua' #设置session加密的密钥

登录视图的实现

简单的登录页面

账号:
密码:
{# #} 没有账号?去注册
@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        name = request.form.get('name')
        password = request.form.get('password')

        user = User.query.filter_by(name=name).first()
        if user:
            if password != user.password:
                return render_template('login.html')
            else:
                session['uid'] = user.id
                session['islogin'] = 1
                return redirect('/index/')
        else:
            cxt = {
                'error': '没有此用户'
            }
            return render_template('login.html', **cxt)

注册视图的实现

简单的注册页面

账号:
密码:
重复密码:
{# 昵称:
#} 性别: 男: 女:

已有账号?去登陆
@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    elif request.method == 'POST':
        name = request.form.get('name')
        password = request.form.get('password')
        password1 = request.form.get('password1')
        gender = request.form.get('gender')

        user = User.query.filter_by(name=name).first()
        if user:
            cxt = {
                'error': '该用户名已存在,请重新创建'
            }
            return render_template('register.html', **cxt)
        else:
            if password != password1:
                cxt = {
                    'error': '两次密码不一致,请重新输入'
                }
                return render_template('register.html', **cxt)
            else:
                user_s = User(name=name, password=int(password), gender=int(gender))
                db.session.add(user_s)
                db.session.commit()

                return redirect('/login/')

退出登录的实现

@app.route('/logout/')
def logout():
    session.clear()
    return redirect('/index/')

首页的展示用户信息以及状态保持,我做的是一个贼简单的相亲网站,只展示与自己相反性别的人

简单的首页


{% if islogin == 1 %}
    

欢迎{{ user.name }}


退出登录

    {% for foo in list_obj %}
  • {{ foo.name }}--{{ foo.set() }}
  • {% endfor %}
{% else %}

去登录


{% endif %}
@app.route('/index/')
def index():
    uid = session.get('uid')
    islogin = session.get('islogin')
    if uid:
        user = User.query.filter_by(id=uid).first()
        obj = User.query.offset(user.gender).all()
        print(obj)
        list_obj = []
        for i in obj:
            if i.id != user.id:
                list_obj.append(i)
        cxt = {
            'user': user,
            'islogin': islogin,
            'obj': obj,
            'list_obj': list_obj
        }
        return render_template('index.html', **cxt)
    else:
        return render_template('index.html')

完整代码(包含数据库创建以及模型类的创建查询)

from flask import Flask, render_template, session, request, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
import pymysql
import redis
pymysql.install_as_MySQLdb()
# 初始化Session对象
f_session = Session()

app = Flask(__name__)
# 设置连接数据库的URL
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/xiangqin'
# 数据库和模型类同步修改
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 查询是会显示原始SQL语句
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

app.config['SECRET_KEY'] = 'laowangaigebi'  # 加密的密钥
app.config['SESSION_USE_SIGNER'] = True  # 是否对发送到浏览器上session的cookie值进行加密
app.config['SESSION_TYPE'] = 'redis'  # session类型为redis
app.config['SESSION_KEY_PREFIX'] = 'session:'  # 保存到session中的值的前缀
app.config['PERMANENT_SESSION_LIFETIME'] = 7200  # 失效时间 秒
app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379', db=4)  # redis数据库连接

# 绑定flask的对象
f_session.init_app(app)

app.config['SECRET_KEY'] = 'xiaohuaxiaohua' #设置session加密的密钥



@app.route('/index/')
def index():
    uid = session.get('uid')
    islogin = session.get('islogin')
    if uid:
        user = User.query.filter_by(id=uid).first()
        obj = User.query.offset(user.gender).all()
        print(obj)
        list_obj = []
        for i in obj:
            if i.id != user.id:
                list_obj.append(i)
        cxt = {
            'user': user,
            'islogin': islogin,
            'obj': obj,
            'list_obj': list_obj
        }
        return render_template('index.html', **cxt)
    else:
        return render_template('index.html')


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        name = request.form.get('name')
        password = request.form.get('password')

        user = User.query.filter_by(name=name).first()
        if user:
            if password != user.password:
                return render_template('login.html')
            else:
                session['uid'] = user.id
                session['islogin'] = 1
                return redirect('/index/')
        else:
            cxt = {
                'error': '没有此用户'
            }
            return render_template('login.html', **cxt)


@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    elif request.method == 'POST':
        name = request.form.get('name')
        password = request.form.get('password')
        password1 = request.form.get('password1')
        gender = request.form.get('gender')

        user = User.query.filter_by(name=name).first()
        if user:
            cxt = {
                'error': '该用户名已存在,请重新创建'
            }
            return render_template('register.html', **cxt)
        else:
            if password != password1:
                cxt = {
                    'error': '两次密码不一致,请重新输入'
                }
                return render_template('register.html', **cxt)
            else:
                user_s = User(name=name, password=int(password), gender=int(gender))
                db.session.add(user_s)
                db.session.commit()

                return redirect('/login/')


@app.route('/logout/')
def logout():
    session.clear()
    return redirect('/index/')



'''创建模型类'''
class User(db.Model):
    # 定义表名
    __tablename__ = 'tbl_user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), unique=True)
    password = db.Column(db.String(32), unique=True)
    gender = db.Column(db.SmallInteger, default=0)

    def set(self):
        if self.gender == 0:
            return '女'
        else:
            return '男'


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
    # db.drop_all()
    # db.create_all()  # 创建表
    #
    # user1 = User(name='zs', password='123456', gender=1)
    # db.session.add(user1)
    # db.session.commit()

客官欢迎下次再来!!!!

你可能感兴趣的:(Flask实现登录注册,以及用session实现状态保持)