day116-Flask的CBV&session高级&Form&DBUtils数据库连接工具

2020-04-22 09:23:58 浏览数 (1)

1.Flask的CBV模式,继承 views.MethodView

代码语言:javascript复制
from flask import Flask, views

app = Flask(__name__)


# 继承 views.MethodView
class LoginView(views.MethodView):
    def get(self):
        return 'get 请求'

    def post(self):
        return 'post 请求'


# 第一个参数是路由,第二个参数是指定类,注意加上 'login',类似于 endpoint 参数
app.add_url_rule('/login', view_func=LoginView.as_view('login'))

if __name__ == '__main__':
    app.run()

2.session写进redis,替换原来的使用机制

代码语言:javascript复制
from flask import Flask, render_template, redirect, request, session
from flask_session import Session
from redis import Redis

app = Flask(__name__)

# 不再有 secret_key

# 配置储存session方式
app.config["SESSION_TYPE"] = "redis"
# 配置redis连接
app.config["SESSION_REDIS"] = Redis("127.0.0.1", 6379)
# 包裹一层 session
Session(app)


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 登录时写进
        session['user'] = request.form.get('username', '')
        return redirect('/detail')
    return render_template('login.html')


# 视图校验器
def is_login(func):
    def inner(*args, **kwargs):
        if not session.get('user', ''):
            return redirect('/')
        res = func(*args, **kwargs)
        return res

    return inner


# 必须声明 endpoint 参数,一般就是被装饰的函数名
@app.route('/detail', endpoint='detail')
@is_login
def detail():
    return 'This is  detail page'


if __name__ == '__main__':
    app.run()

3.Flask的form

3.1视图中

代码语言:javascript复制
from flask import Flask, render_template, request, views

from wtforms.fields import simple, core
from wtforms import Form
from wtforms import validators

app = Flask(__name__)


class RegisterForm(Form):
    username = simple.StringField(
        label='用户名',
        validators=[
            validators.data_required(message='用户名不能为空'),
            validators.length(min=5, max=7, message='长度在不能低于5位,不能高于7位')
        ],
        # 给这个输入框添加一个 class
        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="密码必须位数字"),
        ],
        # widget=widgets.TextInput(),
        render_kw={"class": "my_password"}
    )


class RegisterView(views.MethodView):
    def get(self):
        reg_form_obj = RegisterForm()
        return render_template('register.html', reg_form_obj=reg_form_obj)

    def post(self):
        # 校验数据
        reg_form_obj = RegisterForm(request.form)
        if reg_form_obj.validate():
            return '校验成功'
        return render_template('register.html', reg_form_obj=reg_form_obj)


app.add_url_rule('/reg', view_func=RegisterView.as_view('reg'))
if __name__ == '__main__':
    app.run()

3.2HTML中

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>注册</h1>
<form action="" method="post" novalidate>
    {% for field in  reg_form_obj %}
    <div>{{ field.label }}{{ field }}</div>
    <div>{{ field.errors.0 }}</div>
    {% endfor %}
    <button type="submit">提交</button>
</form>
</body>
</html>

3.3实际效果

3.4其他常用 form

代码语言:javascript复制
email = simple.StringField(
    label="昵称",
    validators=[
        validators.Email(message="格式不正确"),
    ],
    # widget=widgets.TextInput(),
    render_kw={"class": "my_username"}
)

gender = core.RadioField(
    label="性别",
    coerce=int,
    choices=(
        (1, "女"),
        (2, "男")
    ),
    default=1
)

hobby = core.SelectMultipleField(
    label="爱好",
    coerce=int,
    choices=(
        (1, "小姐姐"),
        (2, "小萝莉"),
        (3, "小哥哥"),
        (4, "小正太"),
        (5, "阿姨"),
        (6, "大叔"),
    ),
    default=(1, 2, 5)
)

submit = simple.SubmitField(
    label="提交"
)

4.DBUtils

代码语言:javascript复制
import pymysql
from DBUtils.PooledDB import PooledDB

POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
    maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
    maxshared=3,
    # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
    setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,
    # ping MySQL服务端,检查是否服务可用。
    # 如:0 = None = never, 1 = default = whenever it is requested,
    # 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    host='127.0.0.1',
    port=3306,
    user='root',
    password='',
    database='db7',
    charset='utf8'
)


def func():
    # 建立连接
    conn = POOL.connection()
    # 建立游标,返回字典数据类型
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    # 执行对应 SQL
    cursor.execute('select * from userinfo')
    # 打印结果
    result = cursor.fetchall()
    print(result)
    # 将连接返还给连接池
    conn.close()


func()

0 人点赞