On Thu, Jun 17, 2010 at 1:20 PM, Waldemar Kornewald
<wkornew...@gmail.com> wrote:
> Please take a deeper look at his code. He doesn't use __init__. He
> uses __new__, so each request gets his own View instance.
>
> Instead of
>
> aa = AwesomeAdd()
> foo = aa(3, 5)
>
> the __new__-based approach allows to do this:
>
> foo = AwesomeAdd(3, 5)
>
> IOW, the "constructor" directly returns an HttpResponse (foo) instead
> of an AwesomeAdd instance.

There is no difference between using __init__ and __new__ as long as
you treat the instance as a junkyard for temporary variables. If done
properly, class-based views do _not_ need a separate instance for each
request.

Here's an example of a thread-safe view that works happily with just
one instance:

---- 8< ----

class MyView(object):
    def __init__(self, queryset, template='bar.html'):
        self.qs = queryset
        self.template = template

    def __call__(self, request, id):
        instance = get_object_or_404(self.qs, id=id)
        return direct_to_template(request, self.template, {'object': instance})

# ...

    url(r'^foo/(?P<id>\d+)/', MyView(queryset=Foo.objects.all(),
template='foo.html')),

---- 8< ----

-- 
Patryk Zawadzki

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-develop...@googlegroups.com.
To unsubscribe from this group, send email to 
django-developers+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en.

Reply via email to