this snippet provides a class that can be subclassed for creating views that retain state between requests, you can read more here http://code.google.com/p/django-stateful/ your comments are welcome!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | from django.http import HttpResponse
from django.shortcuts import render_to_response as show_page
from django.conf import settings
from datetime import datetime, timedelta
from threading import Thread
import time
__all__ = ['StatefulView','Page','FinalPage','show_page']
class Page(HttpResponse): pass
class FinalPage(HttpResponse): pass
class StatefulViewType(type):
def __init__(cls, name, bases, dct):
LIVING_STATES = {}
cls._LIVING_STATES = LIVING_STATES
delta = timedelta(seconds=settings.CLEAN_STATES_SECONDS)
def clean_threads():
while True:
for k,(s,updated) in LIVING_STATES.items():
if updated + delta < datetime.today():
try:
del LIVING_STATES[k]
except KeyError:
pass
time.sleep(settings.CLEAN_STATES_SECONDS)
t = Thread(target=clean_threads)
t.daemon = True
t.start()
class StatefulView(object):
__metaclass__ = StatefulViewType
@classmethod
def handle(cls, request, *a, **kw):
keyname = str(cls)+'_'+request.session.session_key
states = cls._LIVING_STATES
if keyname in states:
gen,x = states[keyname]
response = gen.send((request, a, kw))
else:
gen = cls().main()
response = gen.next()
if isinstance(response, FinalPage):
del states[keyname]
else:
states[keyname] = (gen, datetime.now())
return response
def main(self, request, *a, **kw):
raise NotImplementedError("%s must implement 'main'" % self.__class__.__name__)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.