Flask之基础(3)

Flask-Session

pip install Flask-Session  # (为第三方组件)

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

app = Flask(__name__)

1. 指定redis存储session
app.config['SESSION_TYPE'] = 'redis'  # 数据路类型: redis mongodb memcached sqlchemy

2. Redis连接
app.config['SESSION_REDIS'] = Redis('127.0.0.1', 6379, db=15)
# db=15: redis默认有16个数据库, 可用select[0-15]切换, 各个数据库相互独立, 数据隔离.

3. Flask原有的session机制, 比较浪费空间.
Session(app)

@app.route('/index')
def index():
    # 存储session到redis中. 
	session['key'] = 'value'
    # 获取session数据
	print(session.get('key'))
          
	return '已建立session'

app.run(debug = True)
          
'''
存入redis中的key的形式:"session:857a3c6d-e4fe-42b7-af91-5e6d05a8fdab"
存入redis中的key,是客户端cookie中存的key和value的拼接
而存入的value则是二进制类型
'''

WTForms

# 后端逻辑设计

from flask import Flask, request, render_template, redirect
from wtforms.fields import simple, core
from wtforms import Form, validators, widgets

# 建立Form操作对象
class RegisterForm(Form):
    user = simple.StringField(
        label='用户名: ',
        validators=[
            validators.DataRequired(message='用户名不能为空'),
            validators.Length(min=3, max=10, message='长度范围: %(min)d至%(max)d')
        ],
        id='username',              # 设置id
        widget=widgets.FilInput(),  # 更该组件
        render_kw={'class': 'my_class', 'style': 'width: 300px;'},   # 设置属性
    )
    
    pwd = simple.PasswordField(
        label="密码: ",
        validators=[
            validators.Length(max=10, min=6, message="长度范围: %(min)d至%(max)d"),
            validators.Regexp('\d+', message='密码只能为数字')  # 正则匹配
        ],
        id='pwd',
        render_kw={'style': 'width: 300px;'}
    )

    re_pwd = simple.PasswordField(
        label='确认密码: ',
        validators=[
            validators.EqualTo('pwd', message='密码不一致')
        ]
    )

    email = simple.StringField(
        label='邮箱: ',
        validators=[
            validators.Email(message='邮箱格式错误')
        ]
    )

    gender = core.RadioField(
        label='性别: ',
        choices=[ (1, '男'), (2, '女')
        ],
        coerce=int  # 指定数字
    )

    hobby = core.SelectMultipleField(
        label='喜好: ',
        choices=[ (1, '小姐姐'), (2, '小哥哥'),
        ],
        coerce=int
    )

    sub = simple.SubmitField(
        label='登录',
        render_kw={'class': 'bootcss'}
    )
# 视图函数与路由
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        reg = RegisterForm()       #  实例化
        return render_template('register.html', reg=reg)
    else:
        new_reg = RegisterForm(formdata=request.form)   # 将form数据传入Form校验
        if new_reg.validate():                          # 校验数据(是否通过校验)
            return redirect('login')
        else:
            return render_template('register.html', reg = new_reg)
# 模板设计

<form action="" method="post" novalidate>
    {% for field in reg %}         # 循环拿到所有数据
        {% if field.label == '登录' %}
            <p>{{ reg.sub }}</p>
        {% else %}
            <p>{{ field.label }}{{ field }}{{ field.errors.0 }}</p>
        {% endif %}

    {% endfor %}

</form>
posted @ 2019-07-08 15:19  言值  阅读(104)  评论(0编辑  收藏  举报