我知道这很简单,但我不记得应该怎么做。
基本上,我希望函数select_data
返回的结果是
像:
['something','something_a','something_b']
而不喜欢,目前正在返回的内容:
[(u'something',), (u'something_a',)(u'something_b',)]
以下,我使用的代码块:
import sqlalchemy
from sqlalchemy import Table, exc, and_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from configurations import config_loader
hostname = config_loader.get('db_config', 'hostname')
db_name = config_loader.get('db_config', 'db_name')
db_port = config_loader.get('db_config', 'db_port')
login = config_loader.get('db_config', 'db_login')
pwd = config_loader.get('db_config', 'db_pwd')
sample_table = config_loader.get('db_tables', 'some_table')
con_string = 'mysql+mysqlconnector://{login}:{passwd}@{hostname}:{port}/{db}'
engine_str = con_string.format(
login=login, passwd=pwd, hostname=hostname, port=db_port, db=db_name
)
try:
engine = sqlalchemy.create_engine(engine_str, echo=False)
session = sessionmaker(bind=engine)
connection = engine.connect()
session = session(bind=connection)
Base = declarative_base()
except exc.SQLAlchemyError:
raise
def select_data(server):
t = Table(some_table, Base.metadata, autoload_with=engine)
stm = session.query(t.c.data_name).filter(
t.c.server == server
)
return stm.all()
答案 0 :(得分:1)
您的代码返回list的tuples。您应该提取元组,添加以下代码:
raw_data = select_data(server)
data = [item[0] for item in raw_data]
提取的另一种方法:
import operator
raw_data = select_data(server)
data = map(operator.itemgetter(0), raw_data)
有关SQLAlchemy的更多信息。