How to serialize SqlAlchemy result to JSON?

后端 未结 27 1851
说谎
说谎 2020-11-22 09:59

Django has some good automatic serialization of ORM models returned from DB to JSON format.

How to serialize SQLAlchemy query result to JSON format?

I tried

27条回答
  •  孤独总比滥情好
    2020-11-22 10:04

    Even though it's a old post, Maybe I didn't answer the question above, but I want to talk about my serialization, at least it works for me.

    I use FastAPI,SqlAlchemy and MySQL, but I don't use orm model;

    # from sqlalchemy import create_engine
    # from sqlalchemy.orm import sessionmaker
    # engine = create_engine(config.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
    # SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    

    Serialization code

    
    
    import decimal
    import datetime
    
    
    def alchemy_encoder(obj):
        """JSON encoder function for SQLAlchemy special classes."""
        if isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
    
    import json
    from sqlalchemy import text
    
    # db is SessionLocal() object 
    
    app_sql = 'SELECT * FROM app_info ORDER BY app_id LIMIT :page,:page_size'
    
    # The next two are the parameters passed in
    page = 1
    page_size = 10
    
    # execute sql and return a  object
    app_list = db.execute(text(app_sql), {'page': page, 'page_size': page_size})
    
    # serialize
    res = json.loads(json.dumps([dict(r) for r in app_list], default=alchemy_encoder))
    
    

    If it doesn't work, please ignore my answer. I refer to it here

    https://codeandlife.com/2014/12/07/sqlalchemy-results-to-json-the-easy-way/

提交回复
热议问题