登录功能完成:
- js:设置return
- html:设置
- form
- input
session:
- 从`flask`中导入`session`
- 设置`SECRET_KEY`
- 操作字典一样操作`session`:增加用户名`session['username']=`username
py:
- @app.route设置methods
- GET
- POST
- 读取表单数据
- 查询数据库
- 用户名密码对:
- 记住用户名
- 跳转到首页
- 用户名密码不对:
- 用户名密码对:
提示相应错误。
session:
- 从`flask`中导入`session`
- 设置`SECRET_KEY`
操作字典一样操作`session`:增加用户名`session['username']=`username
from flask import Flask,render_template,request,redirect,url_for,session from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db=SQLAlchemy(app) class User(db.Model): #创建一个表,命名user __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) #db.create_all() # 添加数据 # user=User(username='loki',password='6666') # db.session.add(user) # db.session.commit() # 查找数据 # user=User.query.filter(User.username=='loki').first() # print(user.username,user.password) # 修改数据 # user=User.query.filter(User.username=='loki').first() # user.password='68888' # print(user.username,user.password) # db.session.commit() # 删除数据 # user=User.query.filter(User.username=='loki').first() # db.session.delete(user) # db.session.commit() #base页 @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') user=User.query.filter(User.username==username).first() if user: return 'username existed' else: user=User(username=username,password=password) db.session.add(user) db.session.commit() return redirect(url_for('login')) #登录页 @app.route('/login/',methods=['GET','POST']) #get和post方法 def login(): if request.method=='GET': return render_template("login.html") else: username =request.form.get('username') password=request.form.get('password') user=User.query.filter(User.username==username,User.password==password).first() if user: session['user']==username session.permanent=True return redirect(url_for('bese')) else: return 'error username or password' if __name__ == '__main__': app.run()
#enconding utf-8 import os DEBUG = True SECRET_KEY = os.urandom(24) DIALECT='mysql' DRIVER='mysqldb' USERNAME='root' PASSWORD='' HOST='127.0.0.1' PORT='3306' DATABESE='lesson' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@127.0.0.1:3306/lesson?charset=utf8' SQLALCHEMY_TRACK_MODIFICATIONS = False