使用基于类的视图来处理信息?
问题描述:
我一直在试验Django的基于类的视图,并试图编写一个简单的基于类的视图来处理request
中的某些信息,以便“处理器”方法可以使用处理过的信息。使用基于类的视图来处理信息?
我似乎并没有完全理解文档所说的内容,我不确定这应该是Mixin,通用视图还是其他内容。我想制作一个像这样的类:
class MyNewGenericView(View):
redirect_on_error = 'home'
error_message = 'There was an error doing XYZ'
def dispatch(self, request, *args, **kwargs):
try:
self.process_information(request)
# self.process_information2(request)
# self.process_information3(request)
# etc...
except ValueError:
messages.error(request, self.error_message)
return redirect(self.redirect_on_error)
return super(MyNewGenericView, self).dispatch(request, *args, **kwargs)
def process_information(self, request):
# Use get/post information and process it using
# different models, APIs, etc.
self.useful_information1 = 'abc'
self.useful_information2 = 'xyz'
def get_extra_info(self):
# Get some extra information on something
return {'foo':'bar'}
这将允许有人写这样一个观点:
class MyViewDoesRealWork(MyNewGenericView):
def get(self, request, some_info):
return render(request, 'some_template.html',
{'info':self.useful_information1})
def post(self, request, some_info):
# Store some information, maybe using get_extra_info
return render(request, 'some_template.html',
{'info':self.useful_information1})
是上面的代码,以正确的方式去?有没有更简单/更好的方法来做到这一点?这是否会阻止上述功能在另一个通用视图中使用(例如,内置的通用视图)?
答
看来我只是问了一个愚蠢的问题。使用旧式函数观点或新的基于类的意见
class ProcessFooInformation(object):
def __init__(self, request):
self.request = request
@property
def bar(self):
baz = self.request.GET.get('baz', '')
# do something cool to baz and store it in foobar
return foobar
# etc...
然后:
def my_view(request):
foo = ProcessFooInformation(request)
# use foo in whatever way and return a response
return render(request, 'foobar.html', {'foo':foo})
我还做这更
这可以很容易地通过使该处理信息类来实现通过使用属性的懒惰评估来提高效率。
我改编自lazy property evaluation recipe和意见或建议写一个包装:
def lazy_prop(func):
def wrap(self, *args, **kwargs):
if not func.__name__ in self.__dict__:
self.__dict__[func.__name__] = func(self, *args, **kwargs)
return self.__dict__[func.__name__]
return property(wrap)
这每个实例评估方法包裹的价值只有一次,并使用在后续调用存储的值。如果属性评估缓慢,这很有用。
答
+0
我不认为这回答我的问题。我试图使用基于类的视图,以便实际视图可以扩展通用视图并为其处理传入信息。您链接的文章将GET和POST请求简单地分为两种不同的方法,这不是我想要做的。 – Umang
如果您认为有更好的方法,请发表一个答案。 – Umang