SQLAlchemy: Knowing field names and model object values?

I try to adhere to the principles of SOLID object-oriented programming, stay DRY, etc., but my newness to Python / SQLAlchemy / Pyramid makes this very difficult.

I'm trying to take what I now know how the SQLAlchemy model used to create a simple Pyramid Framework object, and use what I know to be a "reflection" in C #, can be called something else in Python ( Introspection? Not sure if this is just my second week with python, but I have a lot of experience working in other languages ​​(C / C ++ / C #, Java, etc.), so the problem seems to match my knowledge with python vocabulary, sorry), find out the field names of the database table and, most importantly, the current field values ​​when I do not know the column names or ANY form from the object but in advance.

Correctly; I do not know that the derp instance has a field called id or name, it just has columns and a value in each of them. And that’s all I care about.

The goal is to be able to use any specific SQLAlchemy data model and convert it into dictionary fields column_name → column_value of simple data types of the kind found in JSON, because I want to ultimately serialize any object that I create in SQLAlchemy for json object, but I will agree to the dictionary, because from there it is trivial as long as the dictionary contains the correct data types. Doing this manually for each object is a violation of too many good clean code rules and will create too much work over time; I could spend another week on this and still save time and effort by doing it right.

So, if I have a class defined in SQLAlchemy as:

class SimpleFooModel(Base):
    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    name = Column(VARCHAR(length=12), nullable=False, index=True)

.. and I have an instance of this value equal (in python):

derp = SimpleFooModel(id=7, name="Foobar")

'derp', , NO OTHER KNOWLEDGE , , python key- > value , JSON import json syslib python.

, 2 , , , ANYWHERE; Google , SO , , , , ; , ( Qaru , , Google , )

, json .., , , , , , , /, , , , , , ( , )

; , getattr - , , , - , ; , , - , , sqlalchmy, /.

:

    from sqlalchemy.inspection import inspect

    obj = inspect(derp, raiseerr=True)

    for key in obj.attrs.keys():
        fields[key] = getattr(derp, key)
        print fields[key]

:

    [Class Name].[Column Name]

.. :

    SimpleFooModel.id
    SimpleFooModel.name

7 "Foobar" id , .

, WHERE, ; , , . , " api", - , , , , , , , ..... , .

, , , derp.id derp.name , SOLID . .

, , 2 , ; SQLAlchemy, , python, , , , , , , .

- , , SOLID ?

EDIT: .

+4
1

:

class BaseModel(object):

    @classmethod
    def _get_keys(cls):
        return sa.orm.class_mapper(cls).c.keys()

    def get_dict(self):
        d = {}
        for k in self._get_keys():
            d[k] = getattr(self, k)
        return d

, , dict {'column_name': 'value'}.

+4

All Articles