Source

django-class-views-experiments / classmethod2.py

Full commit
# Gets the right output. Have to use a classmethod to create the actual view,
# passing constructor arguments to it.

import threading

class View(object):

    @classmethod
    def as_view(cls, *initargs, **initkwargs):
        def view(request, *args, **kwargs):
            self = cls(*initargs, **initkwargs)
            return self.dispatch(request, *args, **kwargs)
        return view

class MyView(View):

    def __init__(self, greeting="Hello"):
        self.foo = []
        self.bar = 0
        self.greeting = greeting

    def dispatch(self, request, *args, **kwargs):
        self.bar += 1
        self.foo.append('x')
        return "%s; %r; %d" % (self.greeting, self.foo, self.bar)

def mydec(func):
    def _wrapper(*args, **kwargs):
        assert isinstance(args[0], HttpRequest)
        return func(*args, **kwargs)
    return _wrapper

view = mydec(MyView.as_view(greeting="Howdy"))

responses = []

class HttpRequest(object):
    pass

def runview():
    global responses
    request = HttpRequest()
    responses.append(view(request))

# Concurrent threads:
t1 = threading.Thread(target=runview)
t2 = threading.Thread(target=runview)

t1.start()
t2.start()
t1.join()
t2.join()

# Serial threads:
runview()
runview()

for r in responses:
    print r