Python psycopg2 how to get data and pass in json
In the example below, we will analyze how to get data from the database, sort by date and return in json format.
Code example
import psycopg2
from psycopg2 import sql
from psycopg2.extras import NamedTupleCursor
from datetime import datetime
class PostgreSQL:
def get_all_data(self):
“” “Returning key-value pair” “”
with self.connect.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cursor:
self.connect.autocommit = True
query = ‘SELECT * FROM stocks ORDER BY date DESC’
cursor.execute(query)
fetch = cursor.fetchall()
# Create new List and Dicts inside it
dic = {}
stocks = [[]
for stock in fetch:
dic[[‘currency’] = stock[[‘currency’],
dic[[‘price’] = stock[[‘price’],
dic[[‘quantity’] = stock[[‘quantity’],
dic[[‘date’] = stock[[‘date’].strftime(“% Y-% m-% d% H:% M:% S”)
stocks.append(dic.copy())
# Sort by date where last row would be last date (just in case)
stocks = sorted(
stocks,
key=lambda x: datetime.strptime(x[[‘date’], ‘% Y-% m-% d% H:% M:% S’), reverse=False
)
return jsondumps(stocks, separators=(‘,’, ‘:’))
Code parsing
connect.cursor
We need to get the object in the form of a dictionary for further processing:
with self.connect.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cursor:
So we get the data in this format:
[RealDictRow([(‘name’, ‘Macerich’), (‘price’, 11.3), (‘quantity’, 200), (‘date’, datetime.datetime(2020, 6, 5, 23, 0, 29, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)))]),
RealDictRow ([(‘name’, ‘Macerich’), (‘price’, 11.3), (‘quantity’, 200), (‘date’, datetime.datetime(2020, 6, 5, 23, 0, 29, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)))])]
If processing is not needed, you can pick up the data in the form of a tuple (but something will not be possible to change inside later):
with self.connect.cursor(cursor_factory=NamedTupleCursor) as cursor:
In this case it will be:
[Record([Record([(‘name’, ‘Macerich’), (‘price’, 11.3), (‘quantity’, 200), (‘date’, datetime.datetime(2020, 6, 5, 23, 0, 29, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)))]),
Record ([(‘name’, ‘Macerich’), (‘price’, 11.3), (‘quantity’, 200), (‘date’, datetime.datetime(2020, 6, 5, 23, 0, 29, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)))])]
If the keys are not needed, it is possible without the contents in brackets:
with self.connect.cursor() as cursor:
We get:
[(148’Macerich’11320022600-057’Sell’datetimedatetime(20206523029tzinfo=psycopg2tzFixedOffsetTimezone(offset=0name=None)))[(148‘Macerich’11320022600-057‘Sell’datetimedatetime(20206523029tzinfo=psycopg2tzFixedOffsetTimezone(offset=0name=None)))…
Date conversion
Here we convert the date:
dic[[‘date’] = stock[[‘date’].strftime(“% Y-% m-% d% H:% M:% S”)
from this:
(‘Date’, datetime.datetime (2020, 6, 5, 23, 0, 29, tzinfo = psycopg2.tz.FixedOffsetTimezone (offset = 0, name = None)))
in such:
‘Date’: ‘2020-06-01 10:17:40’
How to add a dictionary to a sheet inside a loop
To do this, we use the copy () method:
stocks.append(dic.copy())
Sort by date
Also, the code uses sorting by date in a multidimensional list.