【问题标题】:Serializing into dictionary Stored Procedure result using sqlalchemy使用 sqlalchemy 序列化成字典存储过程结果
【发布时间】:2019-04-17 05:17:42
【问题描述】:

我在 mysql 数据库中有存储过程,并使用 sqlalchemy 来获取结果。

    connection = db.engine.raw_connection()
    cursor = connection.cursor()
    cursor.callproc('catalog_get_products_on_catalog', [2000, 10, 0])
    results = cursor.fetchall()
    cursor.close()
    print(results)

我得到元组的结果:

(10, 'abcd')

对于普通的sqlalchemy结果,marshmallow可以用来将结果序列化为字典,是否可以通过在marshmallow中定义一个模式来将元组转换为字典?

【问题讨论】:

    标签: python stored-procedures flask sqlalchemy cursor


    【解决方案1】:

    Marshmallow 目前似乎没有该功能,以下替代方法有效:

    data = db.session.execute(sqlalchemy.text("CALL catalog_get_products_on_catalog(:inShortProductDescriptionLength, :inProductsPerPage, :inStartItem)"),
                                     {'inShortProductDescriptionLength':20, 'inProductsPerPage':10, 'inStartItem':0}).fetchall()
    
    results = []
    for row_number, row in enumerate(data):
        results.append({})
        for column_number, value in enumerate(row):
            results[row_number][row.keys()[column_number]] = value
    

    更新: 它可以简单地通过,

    results = [dict(row) for row in data]

    或者

    results = [*map(dict,data)]

    【讨论】:

    • 或者你可以直接说results = [dict(row) for row in data]
    • results = [*map(dict, data)]
    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多