• FLASK 的Session和MoudelForm插件


    falsk是小而精的框架,但是热度高,

    所有很多爱好者提供了很多扩展插件

    功能强大,美而不足的就是兼容稳定性有时候不太好,不过大部分还是很可以的

    Flask-Session

    flask内置session式写在浏览器上的,感觉和其他框架不太一样,

    现在学习一个写在后台的session

    现在我想写在redis中,怎么操作呢

    先要下载包 : flask-session
    from flask import Flask, render_template
    from flask import views  # 导入视图模块
    from flask import session
    from flask_session import Session  # 导入Session类
    from redis import Redis
    
    app = Flask(__name__, static_folder="static")
    # # # # # # 配置 # # # # # # # #
    red = Redis("127.0.0.1", 6379, db=7)  # 实例化Redis连接
    
    app.config["SESSION_TYPE"] = "redis"  # key大写,value小写!!!
    app.config["SESSION_REDIS"] = red  # 指定连接是Redis实例,让session执行写入redis的方法
    
    Session(app)  # 添加配置
    
    
    # FBV
    @app.route('/')
    def index():
        session["key"] = "strong_key"
        print(session)  # <RedisSession {'_permanent': True, 'key': 'strong_key'}>
        # 浏览器观察key是   session  :8a1561f9-800c-4f03-be69-2ea336c39d39
        # redis中 通过"session:8a1561f9-800c-4f03-be69-2ea336c39d39"获取到value是
        # "x80x03}qx00(X
    x00x00x00_permanentqx01x88Xx03x00x00x00keyqx02X
    x00x00x00strong_keyqx03u."
        return "this's index"
    
    
    # CBV
    class LoginClass(views.MethodView):
    
        def get(self):
    
            return render_template("login.html")
    
        def post(self):
            return "ok"
    
    
    app.add_url_rule("/login", view_func=LoginClass.as_view("login"))
    
    app.run(debug=True, host="127.0.0.1", port="9000")
    seesion_py文件

    源码大概意思

    需要配置的

     

    WTForms - MoudelForm

     后端写页面render到前端的组件

    学过django应该了解form组件

    flask中的第三方库WTForms功能是类似的

    开始写一个简单的登录注册吧。。

    没有拆分,直接写在一个app上了

    from flask import Flask, render_template, request
    from flask import views  # 导入视图模块
    from wtforms.fields import simple, core
    from wtforms import Form
    from wtforms import validators
    
    app = Flask(__name__, static_folder="static")
    
    
    # # # # # # # # # # # # # # # # # # # #
    # # # # # #   MoudelFrom组件  # # # # #
    # # # # # # # # # # # # # # # # # # # #
    
    class LoginForm(Form):
        username = simple.StringField(
            label="用户名",
            validators=[
                validators.DataRequired(message="不能为空"),
                validators.Length(min=3, max=8, message="不能小于3位,不能大于5位")
            ],
            render_kw={"class": "my_username"}
        )
    
        password = simple.PasswordField(
            label="密码",
            validators=[
                validators.DataRequired(message="不能为空"),
                validators.length(min=6, max=6, message="密码必须是6位"),
                validators.Regexp(regex="d+", message="密码必须是数字")
            ],
            render_kw={"class": "my_pwd"}
        )
    
    
    # 注册页面的form
    class RegForm(Form):
        username = simple.StringField(
            label="用户名",
            validators=[
                validators.DataRequired(message="不能为空"),
                validators.Length(min=3, max=6, message="不能小于3位,不能大于6位")
            ],
            # render_kw={""}  不写了默认class:这个字段(username)
        )
    
        password = simple.PasswordField(
            label="密码",
            validators=[
                validators.DataRequired(message="不能为空"),
                validators.Length(min=5, message="密码不能小于6"),
                validators.Regexp(regex="d+", message="密码必须位数字"),
            ],
            render_kw={"class": "reg_pwd"}
        )
    
        re_password = simple.PasswordField(
            label="重复密码",
            validators=[
                validators.EqualTo(fieldname="password", message="两次密码不一致")
            ]
        )
    
        email = simple.StringField(
            label="邮箱",
            validators=[
                validators.Email(message="格式不正确")
            ],
        )
    
        # 性别    单选
        gender = core.RadioField(
            label="性别",
            coerce=int,
            choices=(
                (1, ""), (2, ""), (3, "保密")
            ),
            default=3
        )
    
        # 爱好   多选
        hobby = core.SelectMultipleField(
            label="爱好",
            coerce=int,
            choices=(
                (1, "小姐姐"),
                (2, "小萝莉"),
                (3, "小哥哥"),
                (4, "小正太"),
                (5, "阿姨"),
                (6, "大叔"),
            ),
            default=(1, 2)
        )
    
        submit = simple.SubmitField(
            label="提交"
        )
    
    
    # FBV
    @app.route('/')
    def index():
        return "this's index"
    
    
    # CBV
    class LoginClass(views.MethodView):
    
        def get(self):
            login_form = LoginForm()
            return render_template("login.html", lf=login_form)
    
        def post(self):
            login_form = LoginForm(request.form)
            if login_form.validate():
                return "123"
            else:
                return render_template("login.html", lf=login_form)
    
    
    class RegClass(views.MethodView):
    
        def get(self):
            rf = RegForm()
            return render_template("reg.html", rf=rf)
    
        def post(self):
            rf = RegForm(request.form)
            if rf.validate():
                return "123"
            else:
                return render_template("reg.html", rf=rf)
    
    
    app.add_url_rule("/login", view_func=LoginClass.as_view("login"))
    app.add_url_rule("/reg",view_func=RegClass.as_view("reg"))
    app.run(debug=True, host="127.0.0.1", port="9000")
    app.py文件

    html页面

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta http-equiv="content-Type" charset="UTF-8">
        <meta http-equiv="x-ua-compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Title</title>
    </head>
    <body>
    <form action="" method="post" novalidate>
        {{ lf.username.label }}{{ lf.username }}{{ lf.username.errors.0 }}
        <p>{{ lf.password.label }}{{ lf.password }}{{ lf.password.errors.0 }}</p>
        <input type="submit" value="提交">
        </form>
    </body>
    </html>
    login.html
    <head>
        <meta http-equiv="content-Type" charset="UTF-8">
        <meta http-equiv="x-ua-compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Title</title>
    </head>
    <body>
    <form action="" method="post">
        {% for field in rf %}
            <p>{{ field.label }}{{ field }}{{ field.errors.0 }}</p>
        {% endfor %}
    </form>
    
    </body>
    </html>
    reg.html
  • 相关阅读:
    python数据分析之csv/txt数据的导入和保存
    SQL Server日志文件过大 大日志文件清理方法 不分离数据库
    socket--多进程,多线程服务器
    MYSQL千万级数据表,创建表及字段扩展的几条建议
    常见WEB攻击
    jQuery学习笔记之Ajax用法详解
    redis范围查询应用 数据库 数据库学习 Redis redis范围查询的方法
    CentOS 7下使用RPM安装mysql的方法。
    MySQL Daemon failed to start错误解决办法是什么呢?
    windows无法启动MySQL服务报错1067的解决方法是怎样?
  • 原文地址:https://www.cnblogs.com/clbao/p/10139322.html
Copyright © 2020-2023  润新知