Flask框架第七篇.CBV和Flask-session


1.CBV

优势:先天支持 RestAPI

from flask import Flask,views
?
app = Flask(__name__)  # template_folder, static_folder , static_url_path
?
@app.before_request
def is_login():
    return 1
?
@app.after_request
def is_login(res):
    return res
?
class Login(views.MethodView):  #继承 MethodView,让我当前的 class 可以成为视图类
    
    # methods = ["GET","POST"]
    # decorators = ["is_login"]
    
    def get(self,*args,**kwargs):
        return "get"
?
    def post(self,*args,**kwargs):
        pass
?
    # def primrose(self,*args,**kwargs):
    #     pass
?
app.add_url_rule("/login",
                 endpoint="my_login",
                 view_func=Login.as_view(name="loginlogin")    # view_func.__name__ = "loginlogin"
                 )
?
if __name__ == '__main__':
    app.run()
# 总结 CBV - RestAPI
from flask import views 
?
class Login(views.MethodView):
    def get(*args,**kwargs):
        pass
    
app.add_url_rule("url",
                 endpoint=None,
                 view_func=Login.as_view(name="当前视图函数名,必须唯一,因为他是endpoint"))

2. Flask-session

from flask import Flask,redirect,session
from flask_session import Session
from redis import Redis
?
app = Flask(__name__)
app.secret_key = "%$#*HGTKHGRRLKJ"
?
# app.session_interface  # Flask利用session_interface选择Session存放机制和存放位置
# 连接redis配置
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = Redis(host="127.0.0.1",port=6379,db=10)
?
Session(app)
?
@app.route("/sets")
def sets():
    session['key'] = "张三"
    return "set ok"
?
@app.route("/gets")
def gets():
    return session.get("key")
?
?
if __name__ == '__main__':
    app.run("0.0.0.0",9527)