to do it depending on JSON or not use the after_render hook
after_render is called with the response that is going to be sent,
there you can check to see if it is a dictionary (for JSON case) and
only in that case add the flash data.

On Wed, Sep 14, 2011 at 4:45 PM, julien tayon <[email protected]> wrote:
> Hello,
>
> I try to add to the ouput dict  of the  json expose method the result
> of flash (so that my web integrator can have my business logic
> warning/error/info automagically)
>
> I wanted to know how to hook on @expose (in case json rendere is
> called) in such a way I can alter the dict returned by the controller.
>
> I have 90% of the results with the following code.
>
>
> any hint ?
>
> for instance imagine in the controller :
>
>    @expose('adcop.templates.lost_password')
>    @validate(validators= { 'email' : validators.Email } )
>    @expose('json')
>    @add_flash_to_outdict()
>    def lost(self, *a, **kw):
>        log = logging.getLogger("general")
>        email = kw.get('email')
>        if email is None:
>            flash("No email","error")
>            return dict(page = 'lost', fragment = fragment )
>        #....
>
> here is the actual result :
>
> {"fragment": false, "page": "lost", "_flash": {"status": "error",
> "message": "No email"}}
>
>
> in my a far away file I defined :
>
> from tg import flash, decorators, expose, request
> import logging
> import json
>
> log = logging.getLogger("general")
>
>
> class add_flash_to_outdict(object):
>
>    def __init__(self, error_handler = None, **option ):
>        self.error_handler = error_handler
>        self.option = option or dict()
>
>
>    def __call__(self, func):
>        #@beaker_cache(expire=30,type = 'file')
>        import logging
>        log = logging.getLogger('general')
>        self.log = log
>
>
>        def dict_wrap(*args, **kw):
>            res = func(*args, **kw)
>            if flash and flash.message:
>                res["_flash"] = {
>                    "status" : flash.status or "",
>                    "message" : flash.message or ""
>                }
>            return json.dumps(res)
>
>        brutal = expose(content_type="application/json;charset='%s'" %
> ( request.charset or 'utf-8'))
>        return brutal(dict_wrap)
>
> --
> 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.
>
>

-- 
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