Skip to content

Instantly share code, notes, and snippets.

@allancaffee
Created January 25, 2011 22:50
Show Gist options
  • Save allancaffee/795871 to your computer and use it in GitHub Desktop.
Save allancaffee/795871 to your computer and use it in GitHub Desktop.
Demonstration of bug in mongokit custom type handling
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