Source

django-class-views-experiments / naive.py

Luke Plant 82b7e1d 



Luke Plant d0753c5 



Luke Plant 82b7e1d 


Luke Plant d0753c5 



Luke Plant 82b7e1d 





















Luke Plant d907da2 
Luke Plant 82b7e1d 






Luke Plant d907da2 


Luke Plant 82b7e1d 

Luke Plant d907da2 
Luke Plant 82b7e1d 















# The aim is:
#  * get all the features here
#  * program naively
#  * and yet end up with the output:
#     Howdy; ['x']; 1
#     Howdy; ['x']; 1
#     Howdy; ['x']; 1
#     Howdy; ['x']; 1

# The naive attempt - all features, but the output is:

#   Howdy; ['x']; 1
#   Howdy; ['x', 'x']; 2
#   Howdy; ['x', 'x', 'x']; 3
#   Howdy; ['x', 'x', 'x', 'x']; 4

import threading

class View(object):

    def __call__(self, request, *args, **kwargs):
        return self.dispatch(request, *args, **kwargs)

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