If you use psycopg2, you will need to use a named cursor, otherwise it will try to immediately read all the request data in memory.
cursor = conn.cursor("some_unique_name")
cursor.execute("SELECT aid FROM pgbench_accounts")
for record in cursor:
something(record)
This will retrieve the records from the server in batches of 2000 (the default value itersize), and then upload them in a loop one at a time.
source
share