zoukankan      html  css  js  c++  java
  • 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()
    
  • 相关阅读:
    推荐.Net、C# 逆向反编译四大工具利器
    逆向工具/反编译工具 集合
    秒杀系统-并发处理
    react动态渲染组件
    通过dom获取react节点
    mac上安装windows触摸板不能右键
    STM32F103智能配网mqtt协议EMQ安卓App远程控制LED采集温湿度ESP8266
    itop4412 基于物联网技术的商品支付系统 毕业设计
    STM32F103 单片机最小系统 核心板 C8T6 MINI 飞控 小车 主控制板
    31865 MAX31865 RTD铂电阻温度检测器 PT100至PT1000传感器模块
  • 原文地址:https://www.cnblogs.com/mlhz/p/10256281.html
Copyright © 2011-2022 走看看