[storm] Type checking

Gerdus van Zyl gerdusvanzyl at gmail.com
Sat Feb 14 22:20:06 GMT 2009


I subclass the storm properties for this purpose.
eg:
class dcUnicode(Unicode):
    def __init__(self, name=None, primary=False,size=255, **kwargs):
        self._size = size
        Unicode.__init__(self, name, primary, **kwargs)


    def __set__(self, obj, value):
        if isinstance(value,str):
            value = unicode(value)

        if not value == None and len(value) == 0:
            raise Exception("Empty string not allowed")

        if not value == None and len(value) == self._size:
            raise Exception("string longer than " + str(self._size))
        Unicode.__set__(self, obj, value)

class dcDecimal(Decimal):
    def __init__(self, name=None, primary=False,**kwargs):
        Decimal.__init__(self, name, primary, **kwargs)


    def __set__(self, obj, value):
        if isinstance(value,float):
            value = decimal.Decimal(str(value))

        if isinstance(value,str):
            value = decimal.Decimal(value)

        Decimal.__set__(self, obj, value)




On Sat, Feb 14, 2009 at 7:22 PM, Ben Wilber <benwilber at gmail.com> wrote:
> Hello,
>
> Is there a way to have storm do the type coercion automatically when I
> try to set an attribute?  Example:
>
> class MyTable(object):
>  __storm_table__ = "my_table"
>  id = Int(primary=True)
>  num = Int()
>  name = Unicode()
>
> m = MyTable()
> m.num = "12345" # Raises exception
> m.name = 12345 # Raises exception
>
> both values are easily coerced to the appropriate type, but when
> building up a list (ie from a <form> submit), I have to first check
> for safe input, then coerce from str to int, or unicode etc.  Which
> means that the methods I use to sanitize form input and put it in the
> database have to know/care what type storm expects.  It seems to me
> that this is something that could just be done by storm itself and
> raise a CoercionError or something if the conversion isn't possible
> like m.num = "bob"
>
> Right now I'm just maintaining a dict of dicts (for each attribute)
> containing all the meta info about each:
>
> MyTableDict = {
>  {"num": {"type": 0}},
>  {"name": {"type": u"", "max": 25}},
> }
>
> I use the max attribute to know the max length of the field ( can
> storm do this? )  I type check against each "type" value in the dict
> to determine what I should try to coerce the form input to.
>
> This is probably amateur, but I really don't know of a better way.
>
> Any help would be great.
>
> Thanks!
>
> Ben
>
> --
> storm mailing list
> storm at lists.canonical.com
> Modify settings or unsubscribe at: https://lists.ubuntu.com/mailman/listinfo/storm
>



More information about the storm mailing list