Skip to content
This repository has been archived by the owner on Aug 4, 2022. It is now read-only.

Commit

Permalink
created a web session contrib application. early days
Browse files Browse the repository at this point in the history
  • Loading branch information
quantmind committed Nov 12, 2010
1 parent 85de399 commit 830a7e0
Show file tree
Hide file tree
Showing 11 changed files with 114 additions and 26 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.rst
@@ -1,3 +1,9 @@
Ver. 0.4.1 - Development
============================
* Corrected spelling error in Exception ``ObjectNotFound`` exception class.
* **47 tests**


Ver. 0.4 - 2010 Nov 11
============================
* Development status set to ``beta``.
Expand All @@ -18,7 +24,6 @@ Ver. 0.4 - 2010 Nov 11
structures in a :class:`stdnet.BackendDataServer`.
* Moved ``structures`` module into ``backends`` directory. Internal reorganisation of several modules.
* Added ``app_label`` attribute to :class:`stdnet.orm.DataMetaClass`.
* Added a new module ``stdnet.contrib.djstdnet`` for monitoring objects on the web. The module requires djpcms_.
* **47 tests**

Ver. 0.3.3 - 2010 Sep 13
Expand Down
6 changes: 3 additions & 3 deletions stdnet/backends/base.py
Expand Up @@ -74,7 +74,7 @@ def delete(self, *key):

def get_object(self, meta, name, value):
'''Retrive an object from the database. If object is not available, it raises
an :class:`stdnet.exceptions.ObjectNotFund` exception.
an :class:`stdnet.exceptions.ObjectNotFound` exception.
* *meta* :ref:`database metaclass <database-metaclass>` or model
* *name* name of field (must be unique)
Expand All @@ -84,10 +84,10 @@ def get_object(self, meta, name, value):
else:
id = value
if id is None:
raise ObjectNotFund
raise ObjectNotFound
data = self.hash(meta.basekey()).get(id)
if data is None:
raise ObjectNotFund
raise ObjectNotFound
return meta.make(id,data)

def _get_pipe(self, id, typ, timeout):
Expand Down
1 change: 0 additions & 1 deletion stdnet/backends/structures/structmemcached.py
@@ -1,4 +1,3 @@

from stdnet import structures


Expand Down
6 changes: 3 additions & 3 deletions stdnet/contrib/djstdnet/djlink.py
Expand Up @@ -3,7 +3,7 @@
from django.db.models import signals

from stdnet import orm
from stdnet import ObjectNotFund
from stdnet import ObjectNotFound
from stdnet.orm.query import Manager


Expand All @@ -12,7 +12,7 @@ def remove_linked(sender, instance, **kwargs):
if linked:
try:
linked.objects.get(id = id).delete()
except ObjectNotFund:
except ObjectNotFound:
pass


Expand All @@ -22,7 +22,7 @@ def post_save(sender, instance, **kwargs):
id = instance.id
try:
cobj = linked.objects.get(id = id)
except ObjectNotFund:
except ObjectNotFound:
cobj = linked(id = id)
cobj._linked = obj
cobj.save()
Expand Down
Empty file.
60 changes: 60 additions & 0 deletions stdnet/contrib/sessions/djengine.py
@@ -0,0 +1,60 @@
from datetime import datetime

from django.contrib.sessions.backends.base import SessionBase
from django.conf import settings

from stdnet import ObjectNotFound
from stdnet.contrib.sessions.models import Session, session_settings

session_settings['SECRET_KEY'] = settings.SECRET_KEY

now = datetime.now


class SessionStore(SessionBase):
"""
Implements Redis session store.
"""

def exists(self, session_key):
if db.exists("session:%s" % session_key):
return True
return False

def create(self):
while True:
self.session_key = self._get_new_session_key()
try:
self.save(must_create=True)
except CreateError:
# The key wasn't unique, try again
continue
self.modified = True
return

def save(self, must_create=False):
if must_create:
func = db.setnx
else:
func = db.set
key = "session:%s" % self.session_key
result = func(
key,
self.encode(self._get_session(no_load=must_create)))
if must_create and result is None:
raise CreateError
# The key has been set, set its expiration
db.expire(key, self.get_expiry_age())

def delete(self, session_key=None):
if session_key is None:
session_key = self.session_key
db.delete("session:%s" % session_key)

def load(self):
session_data = db.get("session:%s" % self.session_key)
if session_data is None:
self.create()
return {}
return self.decode(session_data)

34 changes: 34 additions & 0 deletions stdnet/contrib/sessions/models.py
@@ -0,0 +1,34 @@
import base64
import cPickle as pickle

from stdnet import orm
from django.utils.hashcompat import md5_constructor

session_settings = {'SECRET_KEY': None}

class SuspiciousOperation(Exception):
pass


class EncodedPickledObjectField(orm.CharField):

def to_python(self, value):
encoded_data = base64.decodestring(self.data)
pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
if md5_constructor(pickled + session_settings['SECRET_KEY']).hexdigest() != tamper_check:
raise SuspiciousOperation("User tampered with session cookie.")
try:
return pickle.loads(pickled)
except:
return {}

def serialise(self, value):
pickled = pickle.dumps(session_dict)
pickled_md5 = md5_constructor(pickled + session_settings['SECRET_KEY']).hexdigest()
return base64.encodestring(pickled + pickled_md5)


class Session(orm.StdModel):
id = orm.SymbolField(primary_key=True)
data = orm.PickleObjectField()
expiry = orm.DateTimeField(index = False, required = False)
2 changes: 1 addition & 1 deletion stdnet/exceptions.py
Expand Up @@ -37,6 +37,6 @@ class QuerySetError(StdNetException):
evaluation.'''
pass

class ObjectNotFund(QuerySetError):
class ObjectNotFound(QuerySetError):
'''A :class:`QuerySetError` raised when an object is not found.'''
pass
10 changes: 0 additions & 10 deletions stdnet/orm/models.py
Expand Up @@ -38,16 +38,6 @@ def __repr__(self):

def __str__(self):
return ''

def customAttribute(self, name):
'''Override this function to provide custom attributes'''
raise AttributeError("object '%s' has not attribute %s" % (self,name))

def __set_field(self, name, field, value):
if field:
field._set_value(name,self,value)
else:
self.__dict__[name] = value

def save(self, commit = True):
'''Save the instance in the remote :class:`stdnet.HashTable`
Expand Down
6 changes: 3 additions & 3 deletions stdnet/orm/query.py
Expand Up @@ -68,7 +68,7 @@ def get(self):
else:
raise QuerySetError('Get query yielded non unique results')
else:
raise ObjectNotFund
raise ObjectNotFound

def count(self):
'''Return the number of objects in ``self`` without
Expand Down Expand Up @@ -99,7 +99,7 @@ def buildquery(self):
if unique:
try:
self.qset = [meta.cursor.get_object(meta, fargs[0], fargs[1])]
except ObjectNotFund:
except ObjectNotFound:
self.qset = []
else:
if self.eargs:
Expand Down Expand Up @@ -216,7 +216,7 @@ def get_or_create(self, **kwargs):
try:
res = self.get(**kwargs)
created = False
except ObjectNotFund:
except ObjectNotFound:
res = self.model(**kwargs)
res.save()
created = True
Expand Down
8 changes: 4 additions & 4 deletions stdnet/tests/manager.py
Expand Up @@ -37,11 +37,11 @@ def testGet(self):
self.assertEqual(v1,v)

def testGetError(self):
'''Test for a ObjectNotFund exception.'''
'''Test for a ObjectNotFound exception.'''
get1 = lambda : SimpleModel.objects.get(code = 'test2')
get2 = lambda : SimpleModel.objects.get(id = 34)
self.assertRaises(stdnet.ObjectNotFund,get1)
self.assertRaises(stdnet.ObjectNotFund,get2)
self.assertRaises(stdnet.ObjectNotFound,get1)
self.assertRaises(stdnet.ObjectNotFound,get2)

def testEmptyIDFilter(self):
self.assertEqual(SimpleModel.objects.filter(id = 1).count(),0)
Expand All @@ -63,7 +63,7 @@ def testIndexFilter(self):
v1 = SimpleModel.objects.get(group = 'g2')
self.assertEqual(v,v1)
get1 = lambda : SimpleModel.objects.get(group = 'g1')
self.assertRaises(stdnet.ObjectNotFund,get1)
self.assertRaises(stdnet.ObjectNotFound,get1)
v2,created =SimpleModel.objects.get_or_create(code = 'test2', group = 'g2')
self.assertEqual(SimpleModel.objects.filter(group = 'g2').count(),2)
get2 = lambda : SimpleModel.objects.get(group = 'g2')
Expand Down

0 comments on commit 830a7e0

Please sign in to comment.