Source

django-class-views-experiments / magicnew_with_configure.py

# Gets the right output. Getting a response back from calling a class violates
# expectations.

import threading

class View(object):

    def __new__(cls, request, *args, **kwargs):
        self = object.__new__(cls)
        self.__init__()
        return self.dispatch(request, *args, **kwargs)

    @classmethod
    def configure(cls, **kwargs):
        class SubClass(cls):
            pass
        for key, val in kwargs.items():
            setattr(cls, key, val)
        return SubClass

class MyView(View):
    greeting = "Hello"

    def __init__(self):
        self.foo = []
        self.bar = 0

    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.configure(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
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.