flask框架(四)

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.as_view(name='自定义名字')会返回一个函数,name是为这个函数命名,可以通过这个函数进行分发请求等操作。