diff --git a/accountant/api/fields.py b/accountant/api/fields.py new file mode 100644 index 0000000..3327060 --- /dev/null +++ b/accountant/api/fields.py @@ -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 . +""" +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)