1

我一直在试验 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})

上面的代码是正确的方法吗?有没有更简单/更好的方法来做到这一点?这会阻止上述功能在另一个通用视图(例如内置通用视图)中使用吗?

4

2 回答 2

0

看看这个。很好的示例代码。http://www.stereoplex.com/blog/get-and-post-handling-in-django-views

于 2011-08-21T20:07:56.757 回答
0

看来我只是问了一个愚蠢的问题。

这可以通过创建一个处理该信息的类来轻松实现:

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})

我还通过使用属性的惰性评估来提高效率。

我从惰性属性评估配方和评论中改编了一些想法来编写一个包装器:

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)

这对每个实例只评估一次包装方法的值,并在后续调用中使用存储的值。如果属性评估缓慢,这很有用。

于 2011-08-22T22:52:02.367 回答