This is my first attempt to build a json webservice using the Tornado Framework and i have a question about the models design.
Currently i have a Model file (models.py) with all my models that represents my objects like this (this is a logical representation)
class person():
name = StringField()
age = IntField()
class phone():
number = IntField()
person = ReferenceField(Person)
Because i have a lot of methods to implement like person.is_granted(), person.is_admin()( for example ) I was wondering what is the best way (in application design) to declare methods on theses object, should i extend them ? or is it clean to declare methods on the model file definition ?
Thank you for your answers.
In general you will like to have a common ancestor (in terms of inheritance) for all your models, where you implement common methods for all of them. Usually it will be handling of serialization/deserialization, database API abstraction, search, access control and so on. ORMs almost always provide such an ancestor, but sometimes it needs to be extended with application-specific logic.
It is good practice to put method related to models into their objects, especially if this logic should be used in different handlers (like password check, change and generation for user model – they can be used from a bunch of auth-related handlers and model is a good place to put this logic). Meanwhile things like is_admin() where you check whether some other attribute (roles for example) contains certain value can be wrapped in @property decorator to make them look like normal boolean attribute.
Using this approach you separate data-specific logic from application-specific logic in your code so you can wisely spread it between this two modules. When the project grows up you will want to evolve from handlers.py and models.py to handlers and models packages with a bunch of submodules to separate different parts of application and make the code more readable.
P.S.: by the way this really has nothing to do with Tornado or even ORM, for example I use code layout similar to this with plain database API