1

I know this is something really simple to do but i'm not recalling how should i do it.

Basically, I want the result returned from the function select_data to be like:

['something','something_a','something_b']

and not like, what is currently being returned:

[(u'something',), (u'something_a',)(u'something_b',)]

Following, the block of the code that i'm using:

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()
thclpr
  • 5,778
  • 10
  • 54
  • 87

1 Answers1

4

Your code returns list of tuples. You should extract tuples adding the following code:

raw_data = select_data(server)
data = [item[0] for item in raw_data]

One more way to the extracting:

import operator

raw_data = select_data(server)
data = map(operator.itemgetter(0), raw_data)

More information about SQLAlchemy.

Viach Kakovskyi
  • 1,487
  • 1
  • 14
  • 21
  • Solved. it's good practice to force str(item[0]) ? in order to avoid the u' ? – thclpr Jul 12 '17 at 14:30
  • SQLAlchemy returned `unicode` objects and `str` function converts them to string type. The difference is comprehensively explained on the HOWTO: https://docs.python.org/2/howto/unicode.html – Viach Kakovskyi Jul 12 '17 at 14:36