Login

django_stateful

Author:
nubis
Posted:
October 13, 2008
Language:
Python
Version:
1.0
Score:
4 (after 4 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.