完成登录功能,用session记住用户名
Posted 201508030007杨碧茜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了完成登录功能,用session记住用户名相关的知识,希望对你有一定的参考价值。
登录功能完成:
- js:设置return
- html:设置
- form
- input
- py:
- @app.route设置methods
- GET
- POST
- 读取表单数据
- 查询数据库
- 用户名密码对:
- 记住用户名
- 跳转到首页
- 用户名密码不对:
- 提示相应错误。
- 用户名密码对:
session:
- 从`flask`中导入`session`
- 设置`SECRET_KEY`
- 操作字典一样操作`session`:增加用户名`session[‘username‘]=`username
import os SECRET_KEY=os.urandom(24) SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://root:@localhost:3306/misdb?charset=utf8‘ SQLALCHEMY_TRACK_MODIFICATIONS = False
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(50)) # db.create_all() # 添加/删除 # user=User.query.filter(User.username==‘mis1‘,password=‘mis1‘) # db.session.add/delete(user) # db.session.commit() # 查询 # user=User.query.filter(User.username ==‘mis1‘).first() # print(user.username,user.password) # 修改 # user=User.query.filter(User.username==‘mis1‘).first() # user.password=‘123456‘ # user.username=‘mis1‘ # print(user.username,user.password) # db.session.commit() @app.route(‘/‘) def base(): return render_template(‘base.html‘) @app.route(‘/regist/‘,methods=[‘GET‘,‘POST‘]) def regist(): if request.method==‘GET‘: return render_template(‘regist.html‘) else: username=request.form.get(‘username‘) password=request.form.get(‘password‘) nickname = request.form.get(‘nickname‘) user = User.query.filter(User.username==username).first() if user: return ‘username existed‘ else: user=User(username=username,password=password,nickname=nickname) db.seesion.add(user)#数据库操作 db.seesion.commit() return redirect(url_for(‘login‘)) @app.route(‘/login/‘,methods=[‘GET‘,‘POST‘]) def login(): if request.method==‘GET‘: return render_template(‘login.html‘) else: username2=request.form.get(‘username‘) password2=request.form.get(‘password‘) user = User.query.filter(User.username == username2,User.password==password2).first() if user: session[‘user‘] == username2 session.permanent = True return render_template(url_for(‘base‘)) else: return u‘error username or passwod‘ # if user.password==password2: # return redirect(url_for(‘base‘)) # else: # return u‘password error‘ # else: # return u‘username is not existed.‘ if __name__==‘__main__‘: app.run()
以上是关于完成登录功能,用session记住用户名的主要内容,如果未能解决你的问题,请参考以下文章