python-3.x - 从 SQLAlchemy 结果返回字段名称和值

标签 python-3.x sqlalchemy

如何使用 sqlalchemy 获取表列名称和值?

使用我所拥有的,我能够检索:

(2, 'blue', 'square')

但我想得到的是:

{'id': 2, 'color': 'blue', 'type': 'square'}

贝娄,我看完后写的this documentation for version 0.9 :

ConnectionManager.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlalchemy
from sqlalchemy import Table, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


location = 'localhost'
engine_str = 'mysql+mysqlconnector://xx:xx@{}/xx'.format(location)
engine = sqlalchemy.create_engine(engine_str, echo=False)
session = sessionmaker(bind=engine)
connection = engine.connect()
session = session(bind=connection)
metadata = MetaData()
Base = declarative_base()

class SelectType(object):
    """
    Server's details on database
    """
    def go(self, s, cc, pp):
        __table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
        result = s.query(__table__).filter_by(color=cc).filter_by(type=pp).all()
        return result

def select_type(e, p):
    """
    return SelectType result
    """
    try:
        return SelectType().go(session, e, p)
    except:
        raise
    finally:
        session.close()

主文件.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from resources import connection_manager

if __name__ == "__main__":
    try:
for i in connection_manager.select_type('blue', 'square'):
    print(i)

重要的是要注意我正在使用自动加载

最佳答案

使用Query.column_descriptions给你:

class SelectType(object):
    def go(self, s, cc, pp):
        __table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
        result = s.query(__table__).filter_by(color=environment).filter_by(type=pp)
        column_names = [c["name"] for c in result.column_descriptions]
        return [dict(zip(column_names, row)) for row in result.all()]

关于python-3.x - 从 SQLAlchemy 结果返回字段名称和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277548/

相关文章:

python-3.x - 无法识别 PyCharm + conda + pip 包

python - SQLAlchemy 声明式模型的数据验证

csv - 使用 SQLalchemy 读取大文件

python - sqlalchemy 过滤多列

php - 分阶段将 PHP 转换为 django

python-3.x - 如何在 Ubuntu 上将 socket.ntohs(0x0003) 协议(protocol)与 python SOCK_RAW 一起使用?

python - 将字符串中的真值转换为 Int

python - 如何遍历列表并检索最小值的索引但忽略输出列表中的重复项?

python - Sqlalchemy 重用子查询

python - SQLAlchemy 对于只读查询,如何使用 : session. expire() 与 session.commit()?