zoukankan      html  css  js  c++  java
  • 第十一篇 CBV和闪现

    前几篇写的都是FBV

    现在可以了解一下CBV

    CBV

    其实就是把请求方式都写到一个类中

    学过django的一眼应该就明白了

    from flask import Flask, render_template
    from flask import views  # 导入视图模块用于CBV
    
    app = Flask(__name__, static_folder="static")
    
    
    
    # FBV
    @app.route('/')
    def index():
        flash('gang_dan', 'name')
        flash(18, "age")
    
        return "this's index"
    
    
    # CBV
    class LoginClass(views.MethodView):
    
        def get(self):
            return render_template("login.html")
    
        def post(self):
            return "ok"
    
    # 利用源码self.add_url_rule(rule, endpoint, f, **options)可得以下写法
    app.add_url_rule("/login", view_func=LoginClass.as_view("login"))
    
    app.run(debug=True, host="127.0.0.1", port="9000")

    闪现 flush

    from flask import Flask, render_template
    from flask import flash, get_flashed_messages  # flash设置 和取flash值
    from flask import views  # 导入视图模块
    
    app = Flask(__name__, static_folder="static")
    app.secret_key = 'guan_ta_shi_sha_key'  # 使用flash需要设置session  不然报错。。。
    
    
    # FBV
    @app.route('/')
    def index():
        flash('gang_dan', 'name')
        flash(18, "age")
    
        return "this's index"
    
    
    # CBV
    class LoginClass(views.MethodView):
    
        def get(self):
            print(get_flashed_messages("name"))  # 取出所有键值对
            # [('name', 'gang_dan'), ('age', 18)]
            print(get_flashed_messages("age"))  # 取出所有键值对
            # [('name', 'gang_dan'), ('age', 18)]
            print(get_flashed_messages())  # 取出所有的key
            # ['gang_dan', 18]
            return render_template("login.html")
    
        def post(self):
            return "ok"
    
    
    app.add_url_rule("/login", view_func=LoginClass.as_view("login"))
    
    app.run(debug=True, host="127.0.0.1", port="9000")

    先访问一次路由 ‘/’  写入flash,等着再访问 "/login"  获取值后 falsh就没了

    再访问下 "/login" 后  发现打印的全是空列表

  • 相关阅读:
    正则表达式
    装饰练习
    JavaScript练习
    函数fgets和fputs、fread和fwrite、fscanf和fprintf用法小结
    [转载]C#读写文本文件
    c#中绝对路径和相对路径
    C# []、List、Array、ArrayList 区别及应用【转】
    中央子午线的计算方法(转)
    DataTabe的使用
    DataGridView的用法大全(一)
  • 原文地址:https://www.cnblogs.com/clbao/p/10139109.html
Copyright © 2011-2022 走看看