Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation logic in Google App Engine

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?

like image 344
liewl Avatar asked Aug 24 '26 15:08

liewl


1 Answers

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.

like image 118
moraes Avatar answered Aug 26 '26 06:08

moraes