Skip to content
alabid edited this page Aug 7, 2012 · 6 revisions

Models for your whirlwind application should be placed in application/models. By default, whirlwind stores data persistently in mongodb, a no-sql database. Mongodb is accessed via MongoKit. Whirlwind's model structuring is highly dependent on MongoKit, a python module that "brings structured schema and validation layer on top of the great pymongo driver".

Check out the MongoKit documentation here.

Since Models are just abstractions for MongoDB collections, there's an underlying database that's being created for use by all the models you define. You can change the database settings in config/settings.py via the variables db_<option> like db_name, db_port.

Note: For you to be able to use the Models and to use MongoKit functionality, the mongo daemon must be running. You can turn it on via: mongod --dbpath <my-db-path>.

Creating a new Model

To create a new model, we advise you create a new file in application/models that's named after the model you wish to create. For example, to create a User model, create a new file user.py. The first thing you should do is import the necessary modules:

## Necessary modules
from mongokit import *
from whirlwind.db.mongo import Mongo
from tornado import options                                                       

# others I might use
import datetime                                                              
import hashlib, hmac, base64, re

Then define a Model that should be a subclass of the Document MongoKit class. But before declaring the Model class, always register the Model via the whirlwind decorator:

@Mongo.db.connection.register 
class User(Document):                                                        
   structure = {                                                            
                '_id':unicode,                                              
                'email':unicode,                                            
                'roles':list,                                               
                'password':unicode,                                         
                'created_at':datetime.datetime,                             
                'history' : {                                               
                            'last_login' : datetime.datetime,              
                            'num_logins' : long                            
                             },                                             
                'timezone':unicode,                                         
                'suspended_at':datetime.datetime,                           
                }                                                           
   use_dot_notation=True 

Check out the documentation on the Mongokit Document class here.

Interacting with the Model

Having created the model, we'd want to use it to store and retrieve information for our whirlwind application. Every instance of a model maps to a new Mongo document in the collection that models the Mongokit Document. For example, to create a new User as defined above, we do this:

user = User()

# set the attributes of this user here

user.save() # saves a new MongoDB document to its collection in the database

We suggest you wrap the instantiation of your models in a static method in your model class. For example,

@staticmethod
def createUser(username, password):
       user.roles = [username]                                              
       user['_id'] = username                                               
       user.password = hashlib.sha1(password).hexdigest()                   
       user.created_at = datetime.datetime.utcnow()                         
       user.history = {                                                     
                       'num_logins' : 0                                     
                       }                                                    
       return user       

Note that the above method doesn't save the "new user" to the Database. You'll have to manually collect user.save() to persistently save the user instance to the Database.

To retrieve information about instances of a Model (in this case "Users"), you can query the collection which directly maps to the structure of your model. Querying can be done in two places: the Model Definition file or the Controllers.

Querying from the Model Definition File

Mongo.db.ui.users.User.find_one({'_id' : 'alabid'}) # for our User Model example 

Querying from the Controller

# in the subclass of BaseRequest
self.db.users.User.find_one({'_id' : 'alabid'}) # in the controller
# Or
Mongo.db.ui.users.User.find_one({'_id' : 'alabid'}) # as in previous code

Both Mongo.db.ui.users.User and self.db.users.User return a CallableUser which can be queried using the MongoKit methods documented here. The same methods apply to other Models you've defined.

Clone this wiki locally