django视图的上下文修饰符
django-context-decorator的Python项目详细描述
django-context-decorator是一个用于django消除需求的python包 在几乎所有django视图中调用super().get_context_data(**kwargs)。
用法
fromdjango_context_decoratorimportcontextfromdjango.utils.functionalimportcached_propertyfromdjango.views.genericimportTemplateViewclassMyView(TemplateView):template_name='path/to/template.html'@contextdefcontext_variable(self):return'context value'@context@propertydefcontext_property(self):return'context property'@context@cached_propertydefexpensive_context_property(self):return'expensive context property'
现在您可以访问{{ context_variable }},{{ context_property }} 以及模板中的{{ expensive_context_property }}。
请注意:当这个包与@cached_propertydecorator一起工作时, 请确保在上面添加@contextdecorator@cached_property装饰器。
限制
由于使用__set_name__,此包仅限于与python 3.6+一起使用。
开发
所有代码都位于django_context_decorator.py。测试由 pytest来自以test_开头的所有文件。要运行测试,请启动 虚拟环境,安装依赖项,然后运行pytest:
pip install django pytest pytest-cov py.test --cov-report term --cov=django_context_decorator