1. Luke Plant
  2. django-class-views-experiments

Commits

Luke Plant  committed b5aa0b7

Added method that uses a classmethod instead of __new__ to create instance and call dispatch

  • Participants
  • Parent commits d0753c5
  • Branches default

Comments (0)

Files changed (1)

File classmethod.py

View file
+# Gets the right output. Have to use a classmethod to create the actual view,
+# and use configure to set options.
+
+import threading
+
+class View(object):
+
+    @classmethod
+    def as_view(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):
+        return func(*args, **kwargs)
+    return _wrapper
+
+view = mydec(MyView.configure(greeting="Howdy").as_view)
+
+responses = []
+
+def runview():
+    global responses
+    request = object()
+    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