CBV 使用

一. CBV基本使用

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)

1. 写一个类
class LoginView(MethodView):
    def get(self):
        return '我是get请求'

    def post(self):
        return '我是post请求'

2. 注册路由 name 是别名,本质就是 endpoint
app.add_url_rule('/login', view_func=LoginView.as_view('login'))

if __name__ == '__main__':
    app.run()

二. CBV高级

2.1 cbv加装饰器,如何实现

类属性中加入,decorators = [auth, ],属性是一个列表,按照列表顺序,依次给每个方法加装饰器

  class LoginView(MethodView):
      decorators = [auth, ]              # auth: 装饰器名称

源码分析

  def as_view(cls, name, *class_args, **class_kwargs ) :
      ....
      if cls.decorators:
          for decorator in cls.decorators:

            '''
              装饰器原理:
                @auth
                def view():
                本质是  view=auth(view)
            '''

             # 给view加装饰器 >>> 给视图类中的方法加装饰器
             view = decorator(view)
        return view

2.2 as_view的执行流程

  def as_view(cls, name, *class_args, **class_kwargs):
      def view(**kwargs):
          return self.dispatch_request(**kwargs)
      return view

请求来了,路由匹配成功 >>> 执行as_view内的view() >>> self.dispatch_request >>> MethodView的dispatch_request

'''MethodView的dispatch_request'''

   def dispatch_request(self, **kwargs):
        # 在当前视图类中反射,请求方式的小写字符串(get),我们写了get方法
        meth = getattr(self, request.method.lower(), None)
        # 执行get()
        return meth(**kwargs)

2.3 Login.as_view(name='index') name 作用

    if endpoint is None:                                     # endpoint 作用
        endpoint = _endpoint_from_view_func(view_func)       # view_func.__name__
        options["endpoint"] = endpoint

    Login.as_view(name='index') # name 作用

        # 没有传endpoint,Login.as_view('login')是 view函数的内存地址,
        # endpoint会以函数名作为endpoint的值,现在所有函数都是view,必须传入name,来修改调view函数的名字
        app.add_url_rule('/login', view_func=Login.as_view('login'))


        # 如果传了endpoint,别名以endpoint为主,如果不传endpoint,别名以name为主
        app.add_url_rule('/login', view_func=Login.as_view(name='login'),endpoint='xxx')

2.4 cbv 中 methods 的作用

用来控制允许的请求方式

如果不写,写了什么方法,就允许什么请求

  class LoginView(MethodView):
        methods = ['POST']
posted @ 2023-05-15 09:06  codegjj  阅读(17)  评论(0编辑  收藏  举报