accountant/accountant/fields.py

45 lines
1.5 KiB
Python

# vim: set tw=80 ts=4 sw=4 sts=4:
"""
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_restplus 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, model, **kwargs):
"""
:param model: the target model of the object.
"""
self.model = model
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.model.keys()}
# Marshal the dict
return marshal(result, self.model)
def schema(self):
return self.model.__schema__