Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting JSON into validated python objects in Tornado?
    primarykey
    data
    text
    <p>I'm writing a toy app in Tornado and <a href="http://namlook.github.com/mongokit/" rel="nofollow">MongoKit</a> (ORM validator for MongoDB) with basic post/get/put/delete methods. For example, this REST API request 'http://localhost:8888/user' with body {"username": "dhh", "datetime_joined": "2012-08-04 20:05:12"} should create a new document in mongo collection. datetime_joined is a string in JSON, but datetime in MongoKit class. Is there a better way to do that than explicitly converting the string into datetime as shown in the code below? It works fine for datetimes in structure (like 'datetime_joined'), but obviously doesn't work for converting nested datetimes (like 'datetime_created' in the example below). Unless you convert strings into datetimes recursively. To sum up, what's a good practice to convert strings which represent dates into datetimes in MongoKit?</p> <p>Here's my example code for reference:</p> <pre><code>def string_to_datetime(value): if value is not None: return datetime.strptime(value, '%Y-%m-%d %H:%M:%S') return None class User(Document): structure = { 'username': basestring, 'datetime_joined': datetime, 'info': { 'email': basestring, 'datetime_created': datetime } } class APIHandler(tornado.web.RequestHandler): SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT", "OPTIONS") def initialize(self): self.conn = Connection() self.conn.register([User]) self.clazz = self.conn.User def post(self): service = json.loads(self.request.body) service_document = self.clazz() for key in service: if key.startswith('datetime'): service_document[key] = string_to_datetime(service[key]) else: service_document[key] = service[key] service_document.validate() service_document.save() </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload