简体   繁体   中英

Extract string from a Tuple in python with psycopg2

I have written a web.py service in python to access PostGres and get the table names inside the specific database.

CODE:

 def GET(self,r):
          web.header('Access-Control-Allow-Origin',      '*')
          web.header('Access-Control-Allow-Credentials', 'true')
          tables = []
          datasetID = web.input().dataSetID
          cursor = conn.cursor()
          cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
          tablesWithDetails =    cursor.fetchall()
          print tablesWithDetails
          for x in tablesWithDetails:
            x.replace("(", "")
            x.replace(")","")
            tables.append(x)
            print tables;

This prints the table as follows,

[('acam_datasegregationdetails',), ('acam_datasegregationheader',), ('idn_accessinformation',), ('idn_b2cuseraccountmapping',), ('idn_b2cuserdevicemapping',), ('idn_b2cusers',), ('idn_roles',), ('idn_useraccountmapping')]

Needed Output:

['acam_datasegregationdetails', 'acam_datasegregationheader', idn_accessinformation', 'idn_b2cuseraccountmapping', 'idn_b2cuserdevicemapping', 'idn_b2cusers', 'idn_roles', 'idn_useraccountmapping']

Drop that loop and in instead do

tables = [t[0] for t in tablesWithDetails]

It will build a list containing the first element of each tuple in the result set.

Or even simpler (and cheaper), if you want a list then return an array which will be adapted to a list by Psycopg:

cursor.execute("""
    select array_agg(relname)
    from pg_class
    where relkind='r' and relname !~ '^(pg_|sql_)';"
""")
tables = cursor.fetchall()[0][0]

The problem is due this piece of code

tables.append(x)

When you execute cursor.fetchall() you will get a List of Tuples

and when you do for x in tablesWithDetails: you are iterating over the list by one tuple at a time

So when you do tables.append(x) you are appending a single element tuple to the list

To change that you could do this tables.append(x[0]) it appends the first element of the tuple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM