Flask基础知识点2

怒发冲冠,凭栏处、潇潇雨歇。抬望眼,仰天长啸,壮怀激烈。三十功名尘与土,八千里路云和月。莫等闲,白了少年头,空悲切!
靖康耻,犹未雪。臣子恨,何时灭!驾长车,踏破贺兰山缺。壮志饥餐胡虏肉,笑谈渴饮匈奴血。待从头、收拾旧山河,朝天阙。

一、Flask的视图CBV

as_view中的name参数是在路由中endpoint参数不存在时代替endpoint来实现反向解析url的功能的,这个参数是必传的,在endpoint和name同时存在是name作用不生效!!!

两个视图类方法:

  • methods = ["GET","POST"] //视图类的方法
  • decorators = ["wrapper1","wrapper2"] //给类添加装饰器
from flask import Flask,url_for,views

app = Flask(__name__)

class Index(views.MethodView):
    methods = ["GET","POST"]   //视图类的方法
    decorators = ["wrapper1","wrapper2"]   //给类添加装饰器

    def get(self):
        print(url_for("indexs"))
        return "this is GET request"

    def post(self):
        return "this is POST request"

app.add_url_rule("/index", view_func=Index.as_view(name = "indexs"))

app.run()

二、Flask中的插件Flask-Session

  • 下载Flask-Session:
    pip3 install redis
    pip3 install Flask-Session
  • 导入:
    from flask import Flask, session
    from flask_session import Session
    from redis import Redis
  • 配置:
    app.config["SESSION_TYPE"] = "redis"
    app.config["SESSION_REDIS"] = Redis(host="127.0.0.1",port=6379,db=5)
  • 替换:
    Session(app)
  • 使用:
    设置:session["user"] = "aasdf"
    取值:session.get("user")

使用示例:

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

app = Flask(__name__)

app.config["SESSION_TYPE"] = "redis"
app.config["SESSION_REDIS"] = Redis(host="127.0.0.1", port=6379, db=5)
app.secret_key = "wangjifei111"   //可有可无

Session(app)

class Index(views.MethodView):

    def get(self):
        session["name"] = "wangjifei"
        return "this is GET request"

    def post(self):
        return "this is POST request"

app.add_url_rule("/index", view_func=Index.as_view("indexs"))

app.run()

三、Flask中的WTforms的使用(和Django的form非常类似,就不累述了)

  • 下载:
    pip3 install wtforms

  • 简单使用:

from flask import Flask, url_for, views, render_template, request
from flask_session import Session
from flask import session
from redis import Redis
from wtforms.fields import simple, core
from wtforms import Form
from wtforms import validators

app = Flask(__name__)

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

Session(app)


class LoginForm(Form):
    username = simple.StringField(
        label="用户名",
        validators=[
            validators.DataRequired(message="数据不能为空"),
            validators.Length(min=5, max=16, message="大于5小于16")
        ],
        render_kw={"class": "form-control"}
    )

    password = simple.PasswordField(
        label="密码",
        validators=[
            validators.DataRequired(message="数据不能为空"),
            validators.Length(min=5, max=16, message="大于5小于16"),
            validators.Regexp(regex="\d+", message="密码必须为数字")
        ],
        render_kw={"class": "form-control"}
    )

class Login(views.MethodView):
    def get(self):
        loginfm = LoginForm()
        return render_template("login.html", login_html=loginfm)

    def post(self):
        loginfm = LoginForm(request.form)
        if not loginfm.validate():
            return render_template("login.html", login_html=loginfm)
        session["user"] = "wangjifei"
        return "登陆成功"

app.add_url_rule("/login", endpoint="class_login", view_func=Login.as_view(name="login"))
app.run()

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login界面</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <form action="" method="post">
            {% for field in login_html %}
                <div class="form-group">
                    {{ field.label }}:{{ field }}<br>{{ field.errors.0 }}
                </div>
            {% endfor %}
            <input type="submit" class="btn btn-seccess" value="提交">
        </form>
    </div>
</div>
</body>
</html>
  • 略微复杂的使用:
from flask import Flask, url_for, views, render_template, request
from flask_session import Session
from flask import session
from redis import Redis
from wtforms.fields import simple, core
from wtforms import Form
from wtforms import validators

app = Flask(__name__)

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

Session(app)

class RegForm(Form):
    username = simple.StringField(
        label="用户名",
        validators=[
            validators.DataRequired(message="数据不能为空"),
            validators.Length(min=5, max=16, message="大于5小于16")
        ],
        render_kw={"class": "form-control"}
    )

    password = simple.PasswordField(
        label="密码",
        validators=[
            validators.DataRequired(message="数据不能为空"),
            validators.Length(min=5, max=16, message="大于5小于16"),
            validators.Regexp(regex="\d+", message="密码必须为数字")
        ],
        render_kw={"class": "form-control"}
    )

    repassword = simple.PasswordField(
        label="密码",
        validators=[
            validators.DataRequired(message="数据不能为空"),
            validators.EqualTo("password", message="两次密码不一致")
        ],
        render_kw={"class": "form-control"}
    )

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

    hobby = core.SelectMultipleField(
        label="嗜好",
        choices=[(1, "健身"),(2,"喝酒"),(3,"旅游")],
        coerce=int,
        default=1,
        render_kw={"class": "form-control"}
    )

@app.route("/register", methods=["GET", "POST"])
def reg():
    if request.method == "GET":
        regfm = RegForm()
        return render_template("reg.html", reg_html=regfm)
    else:
        regfm = RegForm(request.form)
        if not regfm.validate():
            return render_template("reg.html", reg_html=regfm)

        print(regfm.data.get("hobby"),
              regfm.data.get("gender")
              )

        return "注册成功"

app.run()

reg.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <form action="" method="post">
            {% for field in reg_html %}
                <div class="form-group">
                    {{ field.label }}:{{ field }}<br>{{ field.errors.0 }}
                </div>
            {% endfor %}
            <input type="submit" class="btn btn-seccess" value="提交">
        </form>
    </div>
</div>
</body>
</html>
上一篇:《团队软件过程(修订版)》—第1章1.6节本书结构和流程


下一篇:《响应式Web设计:HTML5和CSS3实践指南》——2.10节基于before及after伪元素添加字符