Created
January 25, 2011 22:50
-
-
Save allancaffee/795871 to your computer and use it in GitHub Desktop.
Demonstration of bug in mongokit custom type handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
from mongokit import CustomType, Document, Connection | |
class CustomDate(CustomType): | |
mongo_type = unicode | |
python_type = datetime.datetime # optional, just for more validation | |
init_type = None # optional, fill the first empty value | |
def to_bson(self, value): | |
"""convert type to a mongodb type""" | |
return unicode(datetime.datetime.strftime(value,'%y-%m-%d')) | |
def to_python(self, value): | |
"""convert type to a python object""" | |
if value is not None: | |
return datetime.datetime.strptime(value, '%y-%m-%d') | |
def validate(self, value, path): | |
"""OPTIONAL : useful to add a validation layer""" | |
if value is not None: | |
pass # do something here | |
class MyDoc(Document): | |
structure = { | |
'dates': {unicode: CustomDate()} | |
} | |
conn = Connection('localhost') | |
conn.register([MyDoc]) | |
doc = conn.test.docs.MyDoc() | |
doc[u'dates'][u'birthdate'] = datetime.datetime(2003,2,1) | |
doc.validate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment