完成登录功能,用session记住用户名
Posted 002邓诺斯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了完成登录功能,用session记住用户名相关的知识,希望对你有一定的参考价值。
from flask import Flask, render_template,request,redirect,url_for,session from flask_sqlalchemy import SQLAlchemy import config from functools import wraps from datetime import datetime app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) class User(db.Model): __tablename__ = ‘user‘ id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(20), nullable=False) password = db.Column(db.String(20), nullable=False) nickname=db.Column(db.String(20)) #db.creat_all() ‘‘‘ #修改密码 user=User.query.filter(User.username==‘mis114‘).first() user.password=‘234567‘ print(user.username,user.password) #删除 user=User.query.filter(User.username==‘mis114‘).first() db.session.delete(user) db.session.commit() #创建用户 user=User(username=‘mis114‘,password=‘mis1114‘) db.session.add(user) db.session.commit() user=User.query.filter(User.username==‘mis1114‘).first() print(user.username,user.password) ‘‘‘ @app.route(‘/‘) def index(): return render_template(‘index.html‘) @app.route(‘/regist/‘, methods=[‘GET‘, ‘POST‘]) def regist(): if request.method==‘GET‘: return render_template(‘regist.html‘) else: # 获取form中的数据,判断用户名是否存在,存到数据库中 username=request.form.get(‘username‘) nickname = request.form.get(‘nickname‘) password=request.form.get(‘password‘) user=User.query.filter(User.username==username).first() # 重定向到登录页 if user: return u‘用户名已存在‘ else: user=User(username=username,nickname=nickname,password=password) db.session.add(user) db.session.commit() return redirect(url_for(‘login‘)) @app.route(‘/login/‘,methods=[‘GET‘,‘POST‘]) def login(): if request.method == ‘GET‘: return render_template(‘login.html‘) else: # 获取form中的数据,判断用户名是否存在,存到数据库中 username = request.form.get(‘username‘) password = request.form.get(‘password‘) user = User.query.filter(User.username == username).first() # 重定向到登录页 #nickname = request.form.get(‘nickname‘) if user: session[‘user‘]=username session.permanent=True return redirect(url_for(‘index‘)) else: return u‘error username or password‘ # if user: # return ‘username existed‘ # else: # user=User(username=username,password=password) # db.session.add(user) # db.session.commit() @app.route(‘/question/‘) def question(): return render_template(‘question.html‘) if __name__ == ‘__main__‘: app.run(debug=True)
import os SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://root:@localhost:3306/test?charset=utf8‘ SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY=os.urandom(24) DIALECT=‘mysql‘ DRIVER=‘mysqldb‘ USERNAME=‘root‘ PASSWORD=‘ROOT‘ HOST=‘127.0.0.1‘ PORT=‘3306‘ DATABASE=‘mis_db‘
以上是关于完成登录功能,用session记住用户名的主要内容,如果未能解决你的问题,请参考以下文章