Hi all, in my current project we use SQLAlchemy, so we need to be able to render SQLAlchemy-instances to JSON.
We cannot simply provide a __json__-method, because the serialization depends on the context. Sometimes, you want to serialize the object without any relations (e.g. only the User-object itself), and sometimes you want the relationships as part of the JSON, too (e.g.: user.posts). That's why marshmallow looks very interesting (http://marshmallow.readthedocs.org), because you can define schemas for serialization. But now I need to find a nice approach for integrating it. My original method looked as follows: @view_config(route_name='user', request_method='GET', renderer='json') def get_own_user(request): user = DBSession.query(User).get(request.authenticated_userid) return user My initial idea to use marshmallow was this (let's assume we already have a UserOutputSchema): @view_config(route_name='user', request_method='GET', renderer='json') def get_own_user(request): user = DBSession.query(User).get(request.authenticated_userid) result = UserOutputSchema().dump(user) # result.data contains the serialization result (a dict) return result.data That approach works, but I don't like it. I prefer my method to return a true User-object (for unit-testing) and not just a dictionary. Transforming the user-object with the marshmallow-schema should happen afterwards, in the rendering-process. What would be the best way to attach a marshmallow-schema to my view-method, so a renderer can use it? a) attaching it to the request? @view_config(route_name='user', request_method='GET', renderer='json') def get_own_user(request): user = DBSession.query(User).get(request.authenticated_userid) request.current_schema = UserOutputSchema() return user b) attaching it inside @view_config somehow? @view_config(route_name='user', request_method='GET', renderer='json', schema=UserOutputSchema()) def get_own_user(request): user = DBSession.query(User).get(request.authenticated_userid) return user c) any other options? Am I missing an obvious approach? Thanks and regards, Martin -- You received this message because you are subscribed to the Google Groups "pylons-discuss" group. To unsubscribe from this group and stop receiving emails from it, send an email to pylons-discuss+unsubscr...@googlegroups.com. To post to this group, send email to pylons-discuss@googlegroups.com. Visit this group at http://groups.google.com/group/pylons-discuss. For more options, visit https://groups.google.com/d/optout.