Flask-session
安装 pip install flask-session
- # -*- coding: utf-8 -*-
- from flask import Flask, session
- from flask_session import Session
- from redis import Redis
- # flask 的session
- # app = Flask(__name__)
- # app.secret_key = 'rfrevtrtr55g'
- #
- # @app.route('/')
- # def index():
- # session['user'] = 'peach'
- # return 'index'
- #
- # app.run(host='0.0.0.0', debug=True)
- # 第三方组件flask-session
- app = Flask(__name__)
- app.config['SESSION_TYPE'] = 'redis' # 保存session到redis
- app.config['SESSION_REDIS'] = Redis(host='192.168.32.71',
- password='redhat',
- db=1) # session redis配置
- Session(app) # 替换flask 中的session, 重写了flask 中session get_interface方法
- # config.setdefault('SESSION_TYPE', 'null') # config是字典, 设置默认值,有的话就不管
- @app.route('/')
- def index():
- session['user'] = 'peach' # 这里发现浏览器里面的session变成了uuid, redis存放了session信息
- # uuid 是从redis中取数据的
- return 'index'
- app.run(host='0.0.0.0', debug=True)
保存的结果 session:uuid
- 127.0.0.1:6379[1]> KEYS *
- 1) "session:554532f2-f92f-4bbf-94c8-639ceb043dce"
- 2) "session:d6f03654-f0a0-4046-933c-503f515499a6"
扩展
Flask-session 如何巧妙替换flask再带的session
WTForms
安装 pip install WTForms
视图
- # -*- coding: utf-8 -*-
- from flask import Flask, render_template,request
- from wtforms.fields import simple, core
- from wtforms import validators
- from wtforms import Form
- app = Flask(__name__, template_folder='../templates')
- class LoginForm(Form):
- username = simple.StringField(
- label="用户名", # 标签标记
- validators=[validators.DataRequired(message="用户名不能为空"),
- validators.Length(min=3,max=8,message="不是长了就是短了")], # 校验条件 可迭代条件
- # description='11111111111', # 描述标记
- id="user_id", # 标签ID
- default=None, # 默认值
- widget=None, # 默认组件(input type="text") 在StringField中已经被实例化了
- render_kw={"class":"my_login"}, # {"class":"my_login"}
- )
- password = simple.PasswordField(
- label="密码", # 标签标记
- validators=[validators.DataRequired(message="密码不能为空"),
- validators.Length(min=3, max=16, message="不是长了就是短了"),
- validators.Email(message="密码必须符合邮箱规则")], # 不知道
- # description='11111111111', # 描述标记
- id="user_id", # 标签ID
- default=None, # 默认值
- widget=None, # 默认组件(input type="text") 在StringField中已经被实例化了
- render_kw={"class": "my_login"}, # {"class":"my_login"}
- )
- @app.route("/",methods=["GET","POST"])
- def index():
- if request.method == "GET":
- fm = LoginForm()
- return render_template("wtf.html",wtf = fm)
- else:
- new_fm = LoginForm(request.form)
- if new_fm.validate():
- return new_fm.data.get("username")
- else:
- return render_template("wtf.html", wtf=new_fm)
- if __name__ == '__main__':
- app.run(host='0.0.0.0' ,debug=True)
前端
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <meta name="viewport" content="width=device-width, initial-scale=1">
- </head>
- <body>
- <form action="" method="post" novalidate>
- {{ wtf.username.label }}
- {{ wtf.username }}
- <p><h1>{{wtf.username.errors.0}}</h1></p>
- <p>
- {{ wtf.password.label }}
- {{ wtf.password }}
- </p>
- <p><h1>{{wtf.password.errors.0}}</h1></p>
- <input type="submit" value="登录">
- </form>
- </body>
- </html>
注册表单演示
- # -*- coding: utf-8 -*-
- from flask import Flask, render_template,request
- from wtforms.fields import simple, core
- from wtforms import validators
- from wtforms import Form
- app = Flask(__name__, template_folder='../templates')
- class RegForm(Form):
- username = simple.StringField(
- label="用户名", # 标签标记
- validators=[validators.DataRequired(message="用户名不能为空"),
- validators.Length(min=3, max=8, message="不是长了就是短了")],) # 校验条件 可迭代条件
- password = simple.PasswordField(
- label="密码", # 标签标记
- validators=[validators.DataRequired(message="密码不能为空"),
- validators.Length(min=3, max=16, message="不是长了就是短了"),
- validators.Email(message="密码必须符合邮箱规则")],) # 校验字段
- regpassword = simple.PasswordField(
- label="确定密码", # 标签标记
- validators=[validators.EqualTo(fieldname="password", message='密码两次不相同')], ) # 确认密码
- gender = core.RadioField(
- label="性别",
- coerce=str, # 数据类型
- choices=(
- ("1", "女"),
- ("2", "男")
- ),
- default="1" # 下面对应上面数据类型int就写1 str 就写"1"
- )
- hobby = core.SelectMultipleField(
- label="爱好",
- validators=[validators.Length(min=2, max=4, message="癖好有问题")],
- coerce=int,
- choices=(
- (1, "fengjie"),
- (2, "luoyufeng"),
- (3, "lixueqin"),
- (4, "wuyifan"),
- (5, "panta")
- ),
- default=(1, 3, 5)
- )
- @app.route('/res', methods=['POST', 'GET'])
- def res():
- if request.method == "GET":
- rf = RegForm()
- return render_template("res.html",rfrf = rf)
- else:
- new_rf = RegForm(request.form)
- if new_rf.validate():
- return new_rf.data.get("username")
- else:
- return render_template("res.html", rf=new_rf)
- if __name__ == '__main__':
- app.run(host='0.0.0.0' ,debug=True)
前端
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>res</title>
- </head>
- <body>
- <form action="" method="post" novalidate>
- {% for foo in rf %} {# 遍历出来的是单个对象 #}
- <p>{{ foo.label }}{{ foo }}{{ foo.errors.0 }}</p>
- {% endfor %}
- <input type="submit" value="注册">
- </form>
- </body>
- </html>