from Cookie import SimpleCookie


class Session(object):

    def __init__(self):
        self.id = None
        self.data = {}

    def __setitem__(self, key, value):
        self.data[key] = value

    def __getitem__(self, key):
        return self.data[key]

    def get(self, key, default=None):
        if key in self.data:
            return self.data[key]
        return default


class SessionMiddleware(object):

    def __init__(self, app, factory,
                 env_key='wsgisession', cookie_key='session_id'):
        self.app = app
        self.factory = factory
        self.env_key = env_key
        self.cookie_key = cookie_key

    def __call__(self, environ, start_response):
        cookie = SimpleCookie()
        if 'HTTP_COOKIE' in environ:
            cookie.load(environ['HTTP_COOKIE'])
        id = None
        if self.cookie_key in cookie:
            id = cookie[self.cookie_key].value
        environ[self.env_key] = self.factory.load(id)

        def middleware_start_response(status, response_headers, exc_info=None):
            id = self.factory.save(environ[self.env_key])
            cookie = SimpleCookie()
            cookie[self.cookie_key] = id
            cookie[self.cookie_key]['path'] = '/'
            cookie_string = cookie[self.cookie_key].OutputString()
            response_headers.append(('Set-Cookie', cookie_string))
            return start_response(status, response_headers, exc_info)
        return self.app(environ, middleware_start_response)

@@ -268,35 +268,149 @@
 def 
-get(self, key, default=None
+__delitem__(self, key):%0A        try:%0A            del self.data%5Bkey%5D%0A        except KeyError:%0A            pass%0A%0A    def __contains__(self, key
 ):%0A 
@@ -416,18 +416,22 @@
         
-if
+return
  key in 
@@ -439,16 +439,177 @@
 elf.data
+%0A%0A    def __iter__(self):%0A        return iter(self.data)%0A%0A    def __len__(self):%0A        return len(self.data)%0A%0A    def get(self, key, default=None):%0A        try
 :%0A      
@@ -628,32 +628,61 @@
  self.data%5Bkey%5D%0A
+        except KeyError:%0A    
         return d

add delete, len and iterable to session via containers magic methods