[sqlalchemy] Re: How to jsonify Query result?
Ok, that approach isn't cool.. I get another one from flask_jsontools and it does what I need! json.dumps(q, cls=DynamicJSONEncoder) Base = declarative_base(cls=JsonSerializableBase) import decimal from datetime import datetime, date from json import JSONEncoder from sqlalchemy import inspect from sqlalchemy.orm.state import InstanceState class DynamicJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, (datetime, date)): return obj.isoformat() elif isinstance(obj, decimal.Decimal): return float(obj) elif hasattr(obj, '__json__'): return obj.__json__() return super(DynamicJSONEncoder, self).default(obj) def get_entity_propnames(entity): ins = entity if isinstance(entity, InstanceState) else inspect(entity) return set(ins.mapper.column_attrs.keys() + ins.mapper.relationships.keys()) def get_entity_loaded_propnames(entity): Get entity property names that are loaded (e.g. won't produce new queries) ins = inspect(entity) keynames = get_entity_propnames(ins) # If the entity is not transient -- exclude unloaded keys # Transient entities won't load these anyway, so it's safe to include all columns and get defaults if not ins.transient: keynames -= ins.unloaded # If the entity is expired -- reload expired attributes as well # Expired attributes are usually unloaded as well! if ins.expired: keynames |= ins.expired_attributes return keynames class JsonSerializableBase(object): Declarative Base mixin to allow objects serialization __json_private__ = set() def __json__(self): return {name: getattr(self, name) for name in get_entity_loaded_propnames(self) - self.__json_private__} -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.
[sqlalchemy] Re: How to jsonify Query result?
I create Serializer class and use it for all my models with: Base = declarative_base(cls=Serializer) But I have one problem! I have Organization model and Service model that has organization = relationship('Organization', backref='services') relationship and I get RuntimeError: maximum recursion depth exceeded while calling a Python object What can I do with that? Help me please! Traceback (most recent call last): File s.py, line 10, in module print repr(r.to_dict()) File /Users/sector119/PycharmProjects/epsilon/epsilon/models/serializer.py, line 31, in to_dict value = self._serialize(key, field.value) File /Users/sector119/PycharmProjects/epsilon/epsilon/models/serializer.py, line 48, in _serialize result.append(cls._serialize(key, v)) File /Users/sector119/PycharmProjects/epsilon/epsilon/models/serializer.py, line 51, in _serialize result = value.to_dict() File /Users/sector119/PycharmProjects/epsilon/epsilon/models/serializer.py, line 31, in to_dict ... ... ... File /Users/sector119/PythonVirtualEnv/epsilon/lib/python2.7/site-packages/sqlalchemy/orm/state.py, line 671, in value self.state.obj(), self.state.class_) File /Users/sector119/PythonVirtualEnv/epsilon/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py, line 233, in __get__ dict_ = instance_dict(instance) RuntimeError: maximum recursion depth exceeded while calling a Python object from datetime import datetime, date from sqlalchemy.inspection import inspect class Serializer(object): __public__ = None __private__ = None def to_dict(self, exclude=(), extra=()): data = {} items = inspect(self).attrs.items() if self.__public__: public = self.__public__ + extra else: public = extra if self.__private__: private = self.__private__ + exclude else: private = exclude for key, field in items: if private and key in private: continue if public and key not in public: continue value = self._serialize(key, field.value) if value: data[key] = value return data @classmethod def _serialize(cls, key, value): print 'Field name: %s' % key if isinstance(value, (datetime, date)): print 'Type date' result = value.isoformat() elif hasattr(value, '__iter__'): print 'Type iterable' result = [] for v in value: result.append(cls._serialize(key, v)) elif isinstance(value, Serializer): print 'Type Serializer' result = value.to_dict() else: print 'Type other' result = value print 'Result %r\n' % result return result -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.
[sqlalchemy] Re: How to jsonify Query result?
The tuples are a variant of python's NamedTuple (sqlalchemy.utils._collections.KeyedTuple) and contain the column names in a `keys` method. You can just write a json adapter that handles instances of KeyedTuple and iterates over their K/V pairs. -- You received this message because you are subscribed to the Google Groups sqlalchemy group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.