• flask之CBV


    一 flask的CBV

    from flask import Flask,views,url_for,render_template
    app = Flask(__name__)
    
    
    @app.route("/index")
    def index():
        return "123"
    
    #CBV
    class Login(views.MethodView):
        methods = ["GET","POST"]#请求方式
        decorators = [app.route] #装饰器
    #注意methods与decotators可以不写 def get(self): print(url_for("my_login")) return render_template("login.html") def post(self): return "登陆成功" app.add_url_rule("/",view_func=Login.as_view("my_login")) if __name__ == '__main__': app.run(debug=True) app.__call__ #对象加括号 会执行__call__方法 app.wsgi_app app.request_class

     注意:CBV中的views.MethodView   这里主要的原因你可以进入到views中的源码中看看,即可知道原因

    views中的源码

    主要注意的部分
    class View(object):
        pass
    
    class MethodViewType(type):
       pass
    
    class MethodView(with_metaclass(MethodViewType, View):
       pass
    
    
    只要看继承关系  由于MethodView继承了MethodViewType,View,因此我们直接使用views.MethodView即可
    

    二  WTForms

    #实现一个简单的web框架
    from werkzeug.serving import run_simple
    from werkzeug.wrappers import Response,Request
    
    @Request.application
    def app(request):
        print(request.path)
        return Response("200 OK!")
    
    
    run_simple("0.0.0.0",5000,app)
    
    # app()
    

    三 偏函数

    # by luffycity.com
    from functools import partial  #partial 偏函数
    
    def ab(a,*args):
        print(a,args)
        return a
    
    par_ab = partial(ab,1)   #偏函数  将1的值给a 但不执行函数
    print(par_ab(2))     #将2给*args  
    print(par_ab)      
    

    四  线程安全 local

    作用:保证数据的一致性和完整性

    #线程安全 
    import time
    import threading
    from threading import local  #首先导入local
    
    class Foo(local):
        pass
    
    foo = Foo()
    """               
    {
        7172:[request,session],  
     #local的作用相当于把数据存成字典,当不同的人来请求时,都只能带走自己的那个数据 这样就形成了数据安全
        8076:[request,session],
        5784:[request,session],
    }
    """
    
    
    def add(i):
        foo.num=i
        time.sleep(1)
        print(foo.num,i,threading.current_thread().ident)   #threading.current_thread().ident获取线程的id
    
    for i in range(20):
        th = threading.Thread(target=add,args=(i,))
        th.start()
    
  • 相关阅读:
    阿里云RDS的mysql数据库连接
    DRF框架400错误信息处理(视图集)
    关于百度Tongji Api的文档补充
    Python几种创建list的方法的效率对比
    手把手教你使用python复杂一点点的装饰器
    Python爬虫常用模块,BeautifulSoup笔记
    LSSS 构造过程
    微信网站应用扫码登陆
    分享一个自用的 Inno Setup 软件打包脚本
    彻底解决:请求被中止: 未能创建 SSL/TLS 安全通道
  • 原文地址:https://www.cnblogs.com/mlhz/p/10256281.html
Copyright © 2020-2023  润新知