Flask基础 3

1. Flask中CBV
2.Flask中的Session插件
3.Flask插件WTForms【前后端不分离】--类似Django的modelform

 

1.Flask 中的 CBV

class Index(views.MethodView):
  # methods = ["POST"]  #定义视图类的请求方式
  # decorators = [war,nei] # 要使用的装饰器,配置此项之后,所有视图函数都会加上装饰器

def get(self):
  return "I am Gay"

def post(self):
  return "I am Les"

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

 

指定endpoint时,以endpoint值作为反向解析名字,但是as_view的name还是要传,不传会报错

endpoint没传,为None时,以as_view的name值作为反向解析的标识

2.Flask中的插件Flask-Session

导入:
  from flask import Flask, session
  from flask_session import Session
  from redis import Redis
配置:

   # 配置session数据库类型
  app.config["SESSION_TYPE"] = "redis" 

  #配置session数据库
  app.config["SESSION_REDIS"] = Redis(host="127.0.0.1",port=6379,db=5)

  #db=5,redis默认有15个数据库db,0-15
替换:

  #替换Flask的session使用Flask-Session
  Session(app)
使用:
  session["user"] = "aasdf"
  session.get("user")

 

  Flask自带的session存储在cookies中

  Flask-Session,session存储在指定的数据库中,cookies中只存储用来查找session的key(uuid4

字符串)

3.Flask中的插件之WTForms

【使用WTForms后,很难前后端分离】   

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

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

  #validators校验器列表,存放字段的校验规则
  render_kw={"class": "jinyinwangba"}   # 为字段增加类、属性键值对
)

class Index(views.MethodView):
  def get(self):
    loginfm = LoginForm()
    return render_template("index.html", fm=loginfm)
  def post(self):
    loginfm = LoginForm(request.form)
    if not loginfm.validate():
      return render_template("index.html", fm=loginfm)
    session["user"] = "I am jinyinwangba"
    return "I am Les"

WTForms
  simple.StringField(
    label = "name"
    validators=[
        validators.校验方法(message="")
        ]
        )
PasswordField

  core.SelectMuitilField(
    label = "name"
    validators=[
    validators.校验方法(message="")
        ],
    choices = [
    [1,"1"],[2,"2"],[3,"3"]
        ],
    coerce = int
    )

传递From
  fm = wtfFrom()
  return render_template("tem.html",fm = fm)

校验:
  fm = wtfFrom(request.form)
  if fm.validate():
  return 成功
  return render_template("tem.html",fm = fm)

 

练习:
学生管理 + 注册登录(Flask CBV,Flask-Session,WTForms) + pymsql

  

posted @ 2018-10-11 16:00  dmyHero  阅读(103)  评论(0)    收藏  举报