import psycopg2 from contextlib import closing import json with open('config.json', 'r') as f: config = json.load(f) database = config['postgres']["database"] user = config['postgres']["user"] password = config['postgres']["password"] host = config['postgres']["host"] port = config['postgres']["port"] # grab sql data with closing connection after it def fetch_sql_data(sql_query): result = [] with closing(psycopg2.connect(database=database, user=user, password=password, host=host, port=port)) as connection: with connection.cursor() as cursor: cursor.execute(sql_query) columns = cursor.description rows = cursor.fetchall() for row in rows: tmp = {} for i in range(len(columns)): tmp[columns[i][0]] = row[i] result.append(tmp) return result if __name__ == '__main__': pass