flask --- 03 .特殊装饰器, CBV , redis ,三方组件
一.特殊装饰器(中间件)
1.before_request
在请求进入视图函数之前
@app.before_request
def look():
2. after_request
在结束视图函数之后,响应返回客户端之前
@app.after_request
def af1(res)
from flask import Flask, request, session, redirect app = Flask(__name__) app.secret_key = "#$%^&*(" @app.before_request # 在请求 之前 def look(): print("be1") if request.path == "/login": return None if session.get("username"): return None else: return redirect("/login") # print(request.method) # return "我是before 我不让你走" @app.before_request # 在请求 之前 def be2(): print("be2") @app.before_request # 在请求 之前 def be3(): print("be3") @app.route("/") def index(): print("index page") return "index page" @app.route("/login") def login(): print("正在登陆......") session["username"] = "username" return "login" @app.after_request def af1(vf_ret): # vf_ret.response[0]=b'2000000 OK!' print("af1") return vf_ret @app.after_request def af2(vf_ret): # vf_ret.response[0]=b'2000000 OK!' print("af2") return vf_ret @app.after_request def af3(vf_ret): # vf_ret.response[0]=b'2000000 OK!' print("af3") return vf_ret if __name__ == '__main__': app.run(debug=True)
打印的结果为:
请求顺序: 正常 : be1 - be2 - be3 - vf - af3 - af2 - af1 异常 : be1 - af3 - af2 - af1
3. errorhandler( )
重定义错误信息
@app.errorhandler(404) def error404(errormessage):
实例:
from flask import Flask, request, session, redirect
app = Flask(__name__)
@app.route("/login")
def login():
print("正在登陆......")
return "login"
@app.errorhandler(404) # 重定义404的错误
def error404(error_message):
print(error_message)
return f"你确定你要查看{request.path}这个页面吗?它已经走丢了,你快去找吧 "
# return redirect("http://baidu.com")
if __name__ == '__main__':
app.run(debug=True)
二. Flask 中的 CBV
基本格式为:
from flask import Flask, request,views app = Flask(__name__) class Login(views.MethodView): # methods=["POST","GET"] # decorators = [] def get(self): return "login" def post(self): return "post_login" app.add_url_rule("/login",view_func=Login.as_view(name="login")) # endpoint = None 默认视图函数名as_view(name="login") name="login" if __name__ == '__main__': app.run(debug=True)
三. windows 下 redis的使用
1.下载安装
①
②
③启动服务端: redis-server
启动客户端: redis-cli
2.redis 模块的使用
①模块下载
②简单使用
from redis import Redis re = Redis(host="127.0.0.1",port=6379,db=1)
# db 的范围在 1~15 类似于15 个库
# 切换时 用 select 1
re.set("kkk","666") print(re.get("kkk"))
四. 三方组件 之 Flask-session
# 1.不想将Session的信息存放在Cookie # 2.将Session存放在Redis # 3.Cookie中保存Session的ID
1.组件下载
2.简单使用
①直接进行初始化
from flask import Flask, request, session from flask_session import Session from redis import Redis # from setting import Set app = Flask(__name__)
#初始化 app.config["SESSION_TYPE"] = "redis" app.config["SESSION_REDIS"] = Redis(host="127.0.0.1",port=6379,db=15) Session(app) @app.route("/login") def login(): session["user"] = "username" return "OK" @app.route("/see") def see(): return session.get("user","还没有session") if __name__ == '__main__': app.run(debug=True) # app.wsgi_app
② 设置setting.py 初始化 进行导入
1.在setting.py中
from redis import Redis class Set(object): SESSION_TYPE = "redis" SESSION_REDIS = Redis()
2.使用时导入
五. 三方组件 之 WTForms
①下载
②简单使用
在 .py 文件中
from flask import Flask,request,render_template app = Flask(__name__) from wtforms.fields import simple,core from wtforms import Form from wtforms import validators class RegForm(Form): username = simple.StringField( label="用户名", validators=[ validators.DataRequired(message="数据不能为空"), validators.Length(min=6,max=10,message="%(min)d数据长度问题%(max)d") ], render_kw={"class":"my_class"}, id="my_username" ) password = simple.PasswordField( label="密码", validators=[ validators.DataRequired(message="数据不能为空"), validators.Length(min=6, max=10, message="%(min)d数据长度问题%(max)d") ], render_kw={"class": "my_class"}, id="my_pwd" ) repassword = simple.PasswordField( label="确认密码", validators=[ validators.EqualTo("password",message="密码不一致") ] ) email = simple.StringField( label="电邮", validators=[ validators.Email(message="邮箱格式有问题例如1@1.1") ] ) hobby = core.SelectMultipleField( # 多选 label="爱好", choices=[ (1,"小姐姐"), (2,"老阿姨"), (3,"小萝莉"), (4,"御姐"), ], default=[2,4], coerce = int ) gender = core.SelectField( # 单选 label="性别", choices=[ (1, "小姐姐"), (2, "小哥哥"), ], default=1, coerce=int ) sub = simple.SubmitField( # 可直接写在 .html 中,更方便 label="登录", render_kw={"class":"red"} ) @app.route("/reg",methods=["POST","get"]) def reg(): if request.method == "GET": rf = RegForm() return render_template("reg.html",rf=rf) else: rf_data = RegForm(request.form) if rf_data.validate(): print(rf_data.data) return f"登陆成功{rf_data.data.get('username')}" else: return render_template("reg.html",rf=rf_data) if __name__ == '__main__': app.run(debug=True)
在 .html 文件中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post" novalidate> {% for field in rf %} <p>{{ field.label }}{{ field }}{{ field.errors.0 }}</p> {% endfor %} </form> </body> </html>