【问题标题】:Please explain the line of code I Mentioned请解释我提到的代码行
【发布时间】:2019-11-01 12:41:43
【问题描述】:

这是我在书中看到的一个 mixin。

from django.core.cache import caches
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie

class CachePageVaryOnCookieMixin:
    cache_name = 'default'

    @classmethod
    def get_timeout(cls):
        if hasattr(cls, 'timeout'):
            return cls.timeout
        cache = caches[cls.cache_name]
        return cache.default_timeout

    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        view = vary_on_cookie(view)
        view = cache_page(timeout = cls.get_timeout(), cache = cls.cache_name)(view)
        return view

在 as_view() view = cache_page(timeout = cls.get_timeout(), cache = cls.cache_name)(view) 最后(视图)有什么用。是类型转换吗?

【问题讨论】:

  • 可能离题,也许检查代码审查?
  • (view) 是一个以view 为参数的callable 的调用。
  • @stephanmg:代码审查是针对您自己编写(或维护)并理解的工作代码。这不是关于 (1) 别人的代码,或 (2) 询问它如何工作或为什么工作。
  • Graipher:很抱歉造成混淆。

标签: python django mixins django-class-based-views


【解决方案1】:

cache_page 是一个函数,它返回另一个接受视图作为参数的函数。这也可以像这样一分为二:

callable_func = cache_page(timeout = cls.get_timeout(), cache = cls.cache_name)
return callable_func(view)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2017-10-30
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多