On Thu, Jun 17, 2010 at 6:08 PM, Patryk Zawadzki <pat...@pld-linux.org> wrote:
> On Thu, Jun 17, 2010 at 2:08 PM, Waldemar Kornewald
> <wkornew...@gmail.com> wrote:
>> On Thu, Jun 17, 2010 at 1:42 PM, Patryk Zawadzki <pat...@pld-linux.org> 
>> wrote:
>>> 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')),
>> This is not at all thread-safe because all requests share the same
>> view instance and thus the same state. Shared state is not thread-safe
>> (unless you introduce some locking mechanism which is not an option
>> here). Thread-safety can only be guaranteed if every thread has its
>> own state. In other words, every request needs his own View instance.
>
> You don't seem to get how threading works.

Let's keep the discussion productive and not talk BS.

> There is no state in this object past the assignments in __init__.
> These are thread-safe as there is only one instance of the object.

The one-instance approach is no more thread-safe than having a global
variable. In your example nothing bad will happen, but once we get to
some real-world reusable views you'll quickly see a need for saving
thread-local state somewhere. We had that problem with Django's Feed
class, for example, where we needed access to the request in one of
the methods and the only workaround was to instantiate a new Feed for
every request and manually inject a _request attribute. The point is
that in a class-based view you normally have lots of methods for
customizing the view's behavior, so either you pass the whole
thread-local state as arguments to every single method (which is
*very* ugly and tedious) or you save that state in self. Also, the
problem with passing lots of arguments around is that it can make
adding more variables to the current state and thus customizability
difficult. There's no way around allowing thread-local state and the
one instance per request approach solves this elegantly.

Bye,
Waldemar Kornewald

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