Serializer provides Easy object serialization. Mimics RoR ActiveRecord serializer.
Example:
from serializer import Serializable
class User(Serializable):
first_name = 'John'
last_name = 'Matrix'
email = 'john.matrix@example.com'
protected_property = 'this value is not included in json'
def attributes(self):
return ['first_name', 'last_name', 'email']
user = User()
user.as_json()
# "{'first_name': 'John', 'last_name': 'Matrix'}"
user.as_json_dict()
# {'first_name': 'John', 'last_name': 'Matrix'}
Serializer supports serializing of deep object structures. Let’s say we have two classes Event and Location and we want to jsonify an event along with its location.
class Location(Serializable):
name = 'Some Location'
def attributes(self):
return ['name']
class Event(Serializable):
name = 'Some Event'
location = Location()
def attributes(self):
return ['name', 'location']
event = Event()
event.as_json()
# "{'name': 'Some Event', 'location': {'name': 'Some Location'}}"
You can fine-grain what gets included in json format by using exclude, include and only parameters.
User.as_json(only=['name', 'email']) # include only name and email
# include all the fields defined in attributes as well as age
User.as_json(include=['age'])
# include all the field defined in attributes but exclude 'email'
User.as_json(include=['email'])
Many times you may have situations where having one default attribute list is not enough. For example you may have multiple views that return user details and many views that return user with only its basic info.
class User(Serializable):
first_name = 'John'
last_name = 'Matrix'
email = 'john.matrix@example.com'
age = 33
is_active = True
def attributes(self):
return ['first_name', 'last_name', 'email']
def attribute_sets(self):
return {'details': ['age', 'is_active']}
user = User()
user.as_json_dict(include='details')
'''
{
'first_name': 'John',
'last_name': 'Matrix',
'email': 'john.matrix@example.com',
'age': 33,
'is_active': True
}
'''
This class mimics the functionality found in RoR ActiveModel. For more info see: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
Returns object attributes as a dictionary with jsonified values
Parameters: |
|
---|
Without any options, the returned JSON string will include all the fields returned by the models attribute() method. For example:
>>> class User(Serializable):
... def attributes(self):
... return [
... 'id',
... 'first_name',
... 'last_name'
... ]
...
>>> user = User()
>>> user.first_name = 'John'
>>> user.last_name = 'Matrix'
>>> user.as_json()
{"id": 1, "first_name": "John", "last_name": "Matrix"}
The ‘only’ and ‘exclude’ options can be used to limit the attributes included. For example:
>>> user.as_json(only=['id', 'first_name'])
{"id": 1, "first_name": "John"}
>>> user.as_json(exclude=['id'])
{"first_name": "John", "last_name": "Matrix"}
To include the result of some additional attributes, method calls, attribute sets or associations on the model use ‘include’.
>>> user.weight = 120
>>> user.as_json(include=['weight'])
{"id": 1, "first_name": "John", "last_name": "Matrix", "weight": 120}
Sometimes its useful to assign aliases for attributes. This can be achieved using keyword ‘as’.
>>> user.as_json(only=['first_name as alias'])
{"alias": "John"}
In order to fine grain what gets included in associations you can use ‘include’ parameter with additional arguments.
>>> user.as_json(include=[('posts', {'include': 'details'})]
{
"id": 1,
"name": "John Matrix",
"first_name": "John",
"last_name": "Matrix",
"weight": 100,
"posts": [
{"id": 1, "author_id": 1, "title": "First post"},
{"id": 2, author_id: 1, "title": "Second post"}
]
}
Second level and higher order associations work as well:
>>> user.as_json('include'= [('posts',
... {
... 'include': [
... ('comments', {'only': ['body']})
... ],
... 'only': ['title']
... }
... )]
{
"id": 1,
"first_name": "John",
"last_name": "Matrix",
"weight": 100,
"posts": [
{
"comments": [
{"body": "1st post!"}, {"body": "Second!"}
],
"title": "Welcome to the weblog"
},
]
}
This method should return a dict with keys as attribute set names and values as desired attribute sets
Attribute sets can be used as a convenient shortcuts in as_json()
Examples:
>>> User(Serializable):
... def attribute_sets(self):
... return {'details': ['id', 'name', 'age']}
>>> User(id=1, name='someone',).as_json(only='details')
{'id': 1, 'name': 'Someone', 'age': 14}
This method is being used by as_json for defining the default json attributes for this model.
Serializable objects can override this and return a list of desired default attributes.
Examples:
>>> User(Serializable):
... def __init__(name, age):
... self.name = name
... self.age = age
...
... def attributes(self):
... return ['name', 'age']
...
>>> User('John', 50).as_json()
{'name': 'John', 'age': 50}
Returns the object attributes serialized in json format
Parameters: |
|
---|
Returns the object attributes serialized in xml format
Parameters: |
|
---|
Registers new dumper for given class type
>>> class MyClassA(object):
... pass
>>> class MyClassB(MyClassA):
... pass
>>> register_dumper('MyClassA', lambda a: 'myclass')
>>> dump_object(MyClassA())
"myclass"
>>> dump_object(MyClassB())
<MyClassB instance>
>>> class MyClassA(object):
... pass
>>> class MyClassB(MyClassA):
... pass
>>> register_dumper(MyClassA, lambda a: 'myclass')
>>> dump_object(MyClassA())
"myclass"
>>> dump_object(MyClassB())
"myclass"
Here you can see the full list of changes between each Serializer release.
Copyright (c) 2012, Konsta Vesterinen
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.