Reputation: 222582
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']
Upvotes: 1
Views: 5105
Reputation: 125284
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]
Upvotes: 7
Reputation: 8335
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
Upvotes: 2