flask flask_session,WTForms

Posted zhangqing979797

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask flask_session,WTForms相关的知识,希望对你有一定的参考价值。

一.Flask_session

本质上,就是是cookie 下的session存储在redis中,方便快速取得session

from flask import Flask,session
from flask_session import Session
from redis import Redis

app=Flask(__name__)
#这两个是必须填写的,在session源码中,
‘‘‘
  if config[‘SESSION_TYPE‘] == ‘redis‘:
            session_interface = RedisSessionInterface(
                config[‘SESSION_REDIS‘], config[‘SESSION_KEY_PREFIX‘],
                config[‘SESSION_USE_SIGNER‘], config[‘SESSION_PERMANENT‘])
‘‘‘

app.config[SESSION_TYPE] = "redis"
app.config["SESSION_REDIS"]=Redis(host=127.0.0.1,port=6379,db=6)

Session(app)
@app.route("/")
def index():
    session["user"]="value"
    return "hello"
if __name__ == __main__:
    app.run(debug=True)


#查看进入redis redis-cli
#选择db select db的序号
#存储在redis get session:c0cdc66b-3ef0-4d0c-8030-a37f14be7e5d

 

二.WTForms

 

本质上就是通过进行类的继承关系快速生成一张form表单,在前端通过后端发送的实例化对象点出他的属性

from flask import Flask, render_template,request
from wtforms import simple, core
from wtforms import validators
from wtforms import Form

app=Flask(__name__)
‘‘‘
源码 进行覆盖
def __init__(self, label=None, validators=None, filters=tuple(),
             description=‘‘, id=None, default=None, widget=None,
             render_kw=None, _form=None, _name=None, _prefix=‘‘,
             _translations=None, _meta=None):
‘‘‘


class LoginForm(Form):
    username=simple.StringField(    #生成的input标签的name:username
        label="用户名",               #字段
        validators=[
            validators.DataRequired(message="用户不能为空"),
            validators.Length(min=3,max=12,message="不是长了就是断了")

        ],             #校验条件
        id="user_id",  #input标签的id
        default=None,  #默认值,当发生select时的默认选择
        widget=None,   # 默认组件(input type="text") 在StringField中已经被实例化了
        render_kw={"class":"my_login"}    #input标签下的类class=my_login

    )
    # 这里PasswordField是继承StringField的 区别在于PasswordField是密文的
    password=simple.PasswordField(

        label="密码",
        validators=[
            validators.DataRequired(message="用户不能为空"),
            validators.Length(min=3, max=12, message="不是长了就是断了"),
            validators.Email(message="密码必须符合邮箱规则")

        ],
        id="user_pwd",
        default=None,
        widget=None,
        render_kw={"class": "my_login"}


    )



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="密码必须符合邮箱规则")
            ])

    repassword=simple.PasswordField(
            label="确认密码",
            validators=[validators.EqualTo(fieldname="password",message="未确认眼神")])



    gender=core.RadioField(  #单选 core下的RadioField
            label="性别",
            coerce=str,
            choices=(("1",""),
                     ("2","")
                     ),
            default="1"  

        )
    hobby=core.SelectMultipleField(    #多选 core下的SelectMultipleField
        label="爱好",
        validators=[validators.Length(min=2,max=4,message="癖好有问题")],
        coerce=int,
        choices=((1,"food"),(2,"eat"),(3,"swim"),(4,"joke"),(5,"love")
    ),
        default=(1,2,3)
        )


@app.route("/",methods=["GET","POST"])
def index():
    if request.method=="GET":
        fm = LoginForm()
        return  render_template("index.html",wtf=fm)
    else:
        new_fm=LoginForm(request.form)
        if new_fm.validate():
            return  new_fm.data.get("username")
        else:
            return render_template("index.html",wtf=new_fm)
@app.route("/reg",methods=["GET","POST"])
def reg():
    if request.method=="GET":
        rf = RegForm()
        return render_template("reg.html",rf=rf)
    else:
        rf = RegForm(request.form)
        if rf.validate():
            return rf.data.get("password")
        else:
            return render_template("reg.html",rf=rf)
        
if __name__ == __main__:
    app.run(debug=True)

 

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post" novalidate>
    {{ wtf.username.label }}
    {{ wtf.username }}
    <p>
    <h2>{{ wtf.username.errors.0 }}</h2></p>
    <p>
        {{ wtf.password.label }}
        {{ wtf.password }}

    </p>
    <p>
    <h1>
        {{ wtf.password.errors.0 }}
    </h1>
    </p>
    <input type="submit" value="登录">


</form>
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

技术分享图片

以上是关于flask flask_session,WTForms的主要内容,如果未能解决你的问题,请参考以下文章

flask flask_session,WTForms

Flask快速入门(17) — flask_session

Flask_Session插件

Flask组件 flask_session

Flask组件 flask_session

flask_session连接redis