accountant/accountant/api/fields.py
2015-06-11 23:38:14 +02:00

41 lines
1.4 KiB
Python

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