In the implementation that connects to the DB (Postgresql) of the Heroku application with Python It was very troublesome for debugging that the result was obtained as an array and the key value could not be determined.
When I looked it up, the following answer was good
http://stackoverflow.com/questions/21158033/query-from-postgresql-using-python-as-dictionary
get_dict_resultset.py
#!/var/bin/python
import psycopg2
import psycopg2.extras
def get_dict_resultset(sql):
conn = psycopg2.connect("dbname=pem host=localhost user=postgres password=Drupal#1008")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute (sql)
results = cur.fetchall()
dict_result = []
for row in results:
dict_result.append(dict(row))
return dict_result
sql = """select * from tablename"""
return get_dict_resultset(sql)
If you use this function, you can easily get the SQL execution result in dict format.
Recommended Posts