Django中的装饰器

1. functools.partial

django 用法:

  • 代码出现的地方

    path = partial(_path, Pattern=RoutePattern)
    re_path = partial(_path, Pattern=RegexPattern)
    
  • 详解

    # 调用path时相当于调用_path('login/', LoginView.as_view(), Pattern=RoutePattern)
    urlpatterns = [
        path('login/', LoginView.as_view()),
    ]
    

2. functools.lru_cache

django:

  • manage.py 命令行执行时fetch_command函数调用get_commands

  • get_commands每次调用都会返回一个dict,当settings文件没有改变的时,返回的值是不变的,使用装饰器则减少了每次启动服务计算commands的时间

    @functools.lru_cache(maxsize=None)
    def get_commands():
        commands = {name: 'django.core' for name in find_commands(__path__[0])}
    
        if not settings.configured:
            return commands
    
        for app_config in reversed(list(apps.get_app_configs())):
            path = os.path.join(app_config.path, 'management')
            commands.update({name: app_config.name for name in find_commands(path)})
    
        return commands
    
  • functools.lru_cache(maxsize=128, typed=False)

    -- maxsize代表缓存的内存占用值,超过这个值之后,之前的结果就会被释放,然后将新的计算结果进行缓存,其值应当设为2的幂
    -- typed若为True,则会把不同的参数类型得到的结果分开保存
    
  • 作用:主要是用来做临时缓存,把耗时的操作结果暂时保存,避免重复计算,比如生成斐波那契数列时,函数后以为结果依赖前两位计算结果值

3. classonlymethod 和 classmethod

  • django CBV 中 类继承View类,urlpattern里面调用as_view实现一个接口不同不同调用方式走不同的逻辑,as_view方法使用@classonlymethod装饰器

  • 源码

    ```python
    class classonlymethod(classmethod):
        def __get__(self, instance, cls=None):
            if instance is not None:
                raise AttributeError("This method is available only on the class, not on instances.")
            return super().__get__(instance, cls)
    ```
    
  • 源码可以看出classonlymethod和classmethod的区别即为,classonlymethod只能由类调用,实例对象调用时会抛出对象异常

上一篇:C++设计模式——命令模式 Command


下一篇:[CLI] Create a Hybrid Single-Multi Command Node.js CLI with Oclif and TypeScript