• flask框架(四)——flask CBV视图类解析


    CBV视图类的两种基本写法

    #第一种写法
    class
    IndexView(views.View): methods = ['GET'] decorators = [auth, ] def dispatch_request(self): print('Index') return 'Index!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))
    #第二种方法(通常使用这种) class IndexView(views.MethodView): methods = ['GET','POST'] #指定可以接收的方法有什么,默认可以不写 decorators = [auth, ] #指定自定义的装饰器 def get(self): return 'Index.GET' def post(self): return 'Index.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) #name=('index')是取别名的意思

    总结流程:

    1.先从flask中导入views

    2.写一个类一定要继承views.MethodView

    3.在类中写methods = ['GET','POST'],可以指定可接受的请求类型,默认是两种都行

    4.在类中写decorators = [auth,]可以指定装饰器,第一个装饰器是最里层函数依次往外包裹

    5.在类中写def get(self):用于获取get请求

    6.在类中写def post(self):用于获取post请求

    7.添加路由的方法使用

    app.add_url_rule('路由', view_func=IndexView.as_view(name='自定义一个端点名字'))  

    其原理是IndexView.ad_view(name='自定义名字')会返回一个函数,name是为这个函数命名,可以通过这个函数进行分发请求等操作

  • 相关阅读:
    编译Android源码
    Android Studio 更新
    ANDROID:替换系统桌面
    Linux目录树与文件系统
    主引导记录MBR
    Android开发使用run-as获取应用数据
    桥接模式
    工厂方法模式
    Floyd's Cycle Detection Algorithm
    用两个stack实现一个队列
  • 原文地址:https://www.cnblogs.com/wangcuican/p/11838814.html
Copyright © 2020-2023  润新知