Part of the app I'm coding is structured roughly like this:
class PostModel(db.Model):
some_property = db.WhateverProperty()
some_other_property = db.WhateverProperty()
class PostHandler(webapp.RequestHandler):
def get(self):
#code to generate form
def post(self):
#code to validate input from form
#create entity and put() it to datastore if input passes the validation
Now, from what I read about MVC, this validation logic should be in the model, right? So, should I do something like this instead?
class PostModel(db.Model):
some_property = db.WhateverProperty()
some_other_property = db.WhateverProperty()
@staticmethod
def validation_logic(form_input):
#throw exceptions if validation fails
@staticmethod
def save_to_datastore(form_input):
#this would assume data already passed validation
#create entity and save it
class PostHandler(webapp.RequestHandler):
def get(self):
#code to generate form
def post(self):
try:
PostModel.validation_logic(form_input)
except CustomException,e:
self.redirect('/errorpage?msg='+e.msg)
PostModel.save_to_datastore(form_input)
Is this good MVC form?
There are a few ways of doing it. Some form libraries will do most of the basic validation, but some things are inevitably left out when you have more complex data.
I think it is a good idea to pass a dictionary of values to a @classmethod of the model, and let it validate the data. I usually have a class method like your save_to_datastore(), basically used to validate and assemble an entity to be saved instead of doing it in the handler. I prefer to not have in a handler datastore specific things. For example: use model class methods for queries instead of creating queries directly in the handler. It makes you think the model as an api, is easier to maintain and keep track of indexes etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With