Add Object marshaller.
This commit is contained in:
parent
906430bb5b
commit
aa1550afe3
40
accountant/api/fields.py
Normal file
40
accountant/api/fields.py
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
"""
|
||||||
|
This file is part of Accountant.
|
||||||
|
|
||||||
|
Accountant is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
Accountant is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with Accountant. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
from flask.ext.restful import marshal, fields
|
||||||
|
|
||||||
|
|
||||||
|
class Object(fields.Raw):
|
||||||
|
"""
|
||||||
|
Field to marshal an object with fields.
|
||||||
|
|
||||||
|
SQLAlchemy rows are viewed as tuples by Restful marshaller, and must be
|
||||||
|
translated into a dict before marshaling.
|
||||||
|
"""
|
||||||
|
def __init__(self, fields, **kwargs):
|
||||||
|
"""
|
||||||
|
:param fields: field declaration.
|
||||||
|
"""
|
||||||
|
self.fields = fields
|
||||||
|
|
||||||
|
super(Object, self).__init__(**kwargs)
|
||||||
|
|
||||||
|
def format(self, value):
|
||||||
|
# First transform object in dict with fields in attribute.
|
||||||
|
result = {key: getattr(value, key, None) for key in self.fields.keys()}
|
||||||
|
|
||||||
|
# Marshal the dict
|
||||||
|
return marshal(result, self.fields)
|
Loading…
Reference in New Issue
Block a user