登录功能完成:
- js:设置return
- html:设置
- form
- input
- 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):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=TabError, autoincrement=True)
username = db.Column(db.String(20), nullable=False)
password = db.Column(db.String(20), nullable=False)
# nickname = db.Column(db.String(20))
# 查询删除
# user = User.query.filter(User.username == 'lin').first()
# db.session.delete(user)
# db.session.commit()
# 修改
# user = User.query.filter(User.username == 'lin').first()
# user.password = '1234'
# print(user.username,user.password)
# db.session.commit()
# 增加
# user = User(username = 'lin',password = 'lin')
# db.session.add(user)
# db.session.commit()
db.create_all()
@app.route('/')
def jianshu():
return render_template('jianshu.html')
@app.route("/login/", methods=['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).first()
if user:
session['user'] = username
session.permanent = True
return redirect(url_for('jianshu'))
else:
return 'error username or password'
@app.route("/enroll/", methods=['GET', 'POST'])
def enroll():
if request.method == 'GET':
return render_template('enroll.html')
else:
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter(User.username == username).first()
if user:
return 'username exited'
else:
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
@app.route("/post/")
def post():
return render_template('post.html')
if __name__ == '__main__':
app.run(debug=True)