在基于Django类的视图中设置实例变量是否可行? [英] Is it okay to set instance variables in a Django class based view?
问题描述
我尝试Django的基于类的视图(CBV)。
I trying out Django's class based views (CBVs).
class BlahView(TemplateView):
template_name = 'blah/blah.html'
def get_context_data(self, **kwargs):
#code...
def get(self, request, **kwargs):
#more code...
现在,我知道我可以得到请求参数从self.request。现在说我想解析这些请求参数并将它们存储在类中。可以将它们存储在 self.xxx
中吗?现在,显然是基于课堂的工作原理,这似乎很简单。
Now, I know that I can get the request params from self.request. Now say I want to parse these request params and store them within the class. Can I store those in self.xxx
? Now, obviously based on how classes work, this seems straightforward.
但是,我无法弄清楚控制流程,看看查看
(超级 TemplateView
)。 来源提到 as_view()
成为入门点
But I can't make out the flow of control, looking at the definition of View
(superclass of TemplateView
). The source mentions as_view()
to be the 'entry-point'
我以为在开头设置我的实例变量, get_context_data()
但是似乎没有进行初始化。
I thought of setting my instance variables at the beginning of get_context_data()
but that doesn't seem right to do initialization there.
我可以定义一个 __ init __()
为我的CBV?
如果是这样,是否有线程问题或多个页面访问可能与解析的数据的全局实例一起工作?
Can I define an __init__()
for my CBV?
If so, will there be threading issues or something where multiple page-accesses possibly work with a global instance of my parsed data?
我知道这听起来像有点混乱,但我只是在CBV中的代码流中感到困惑。
I know this sounds a bit messy, but I'm just a bit confused with the code flow in CBVs.
推荐答案
根据源, django.views.generic.base。在django启动时,as_view()返回一个函数,view.as_view
:
-
视图
,不 - 请求,
view()
被称为,它会实例化类并调用dispatch()
- 类实例是线程安全
- on django startup, as_view() returns a function
view
, which is not called - on request,
view()
is called, it instantiates the class and callsdispatch()
- the class instance is thread safe
根据 的源
django.views.generic.base.Vie这个请求对象在这个时候超出了范围,所以你不能在你自己的构造函数重载中解析它。
According to the source of django.views.generic.base.View.__init__
, the request object is out of scope at this point so you can't parse it in your own constructor overload.
然而,您可以解析请求并设置类视图实例属性在 django.views.generic.base.View.dispatch
的重载中,根据源:
However, you could parse the request and set class view instance attributes in an overload of django.views.generic.base.View.dispatch
, this is safe according to the source:
class YourView(SomeView):
def dispatch(self, request, *args, **kwargs):
# parse the request here ie.
self.foo = request.GET.get('foo', False)
# call the view
return super(YourView, self).dispatch(request, *args, **kwargs)
这篇关于在基于Django类的视图中设置实例变量是否可行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!