开发者

django-piston : Overriding default serialization in emitters

开发者 https://www.devze.com 2023-01-20 08:08 出处:网络
I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.

I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.

More precisely, my models are subclassed from a special Model开发者_如何学Go class, which inherits from django.db.models.base.ModelBase, but cannot be serialized as regular django models ... Therefore, I would like to override the serializer for all subclasses of this special Model class.

I don't know piston well ... I've looked at the code, and the mapping type->serializer (for base types) seems to be hard-coded.

Does anybody know if there is a standard way to override it ???


You can do the serialization yourself. The handlers only expect and return a python dictionary. For this though, you can't just plug it into a model. Create your own resource handler for your base type, which is capable of building your Model from a dict.

class ModelHandler(HandlerBase):
    allowed_methods = ('Get',)

    def read(self, request, id=None):
        if id is not None:
            m = Model.objects.get(id=id)

        ret = {}
        ret['field'] = m.field

        return ret


Ok ... I couldn't have it working, so I took some code that I had written myself some time ago, made it cleaner, it ended-up in a full Python serialization framework SpitEat. I have begun writing some documentation, but it's a work in progress.

I have given-up using piston, since it is not the first time it disappoints me by its lack of flexibility on (de)serialization operations.

SpitEat aims to be fully customizable, (by seeing serialization from a more abstract point of view than just "django objects") and provides serializers for Django, tested, but not so well documented yet, and with features that are still missing (again it is a work in progress).

0

精彩评论

暂无评论...
验证码 换一张
取 消