On Wednesday 20 August 2008 08:34:48 Felix Schwarz wrote:
> Matt Wilson schrieb:
> > On Aug 19, 9:34 pm, Jorge Godoy <[EMAIL PROTECTED]> wrote:
> >>         2. You want to receive any user_id and make it an integer, but
> >> want to raise an exception if it isn't in the database?
>
> (...)
>
> > Yeah, I figured that's *how* I could do it.  I'm curious about if I
> > *should* do it this way.  Is there some subtle danger in this
> > approach?
>
> I do something similar which does work really well for me: I have validator
> which transforms a given id into the appropriate model object (so I have a
> specific validator for every model object [1]) and that does work really
> well.
>
> Say the user want to view an invoice. The controller function just gets the
> invoice id but inside the function I can just work on the invoice and don't
> have to care about looking in the db, handling errors (not found, no db
> connection) etc.
>
> So if you try to validate ids, then use the validator to transform these
> ids into model objects. Else you gain next to nothing because the id could
> be deleted in the db by the time your code enters your controller function.

It gets even easier:


class ModelValidator(Int):

    messages = {
        'unknown_id': _("No %(model_class)r with id %(id)i")
        }


    def __init__(self, model_class, *args, **kwargs):
        self.model_class = model_class
        Int.__init__(self, *args, **kwargs)


    def _to_python(self, value, state):
        id_ = Int._to_python(self, value, state)
        obj = self.model_class.get(id_)
        if obj is None and self.not_empty:
            msg = self.message(
                'unknown_id',
                state,
                model_class=self.model_class,
                id=id_
                )
            raise Invalid(msg, value, state)
        return obj


    def _from_python(self, value, state):
        if value is not None:
            return str(value.id)
        return ""


it subclasses the Int-validator (because we want its behavior first), and then 
tries to resolve for a passed model-object.

All you do is 

ModelValidator(ModelClass)

Not even 2 or three lines :)

Diez

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to