I\'m building a web app in Python (using Flask). I do not intend to use SQLAlchemy or similar ORM system, rather I\'m going to use Psycopg2 directly.
Should I open a new
Yeah connection pooling will help but yes you have to find out the right numbers for live connection or pool size based on which load will be on database.
from psycopg2.pool import SimpleConnectionPool
from contextlib import contextmanager
dbConnection = "dbname='dbname' user='postgres' host='localhost' password='postgres'"
# pool define with 10 live connections
connectionpool = SimpleConnectionPool(1,10,dsn=dbConnection)
@contextmanager
def getcursor():
con = connectionpool.getconn()
try:
yield con.cursor()
finally:
connectionpool.putconn(con)
def main_work():
try:
# with here will take care of put connection when its done
with getcursor() as cur:
cur.execute("select * from \"TableName\"")
result_set = cur.fetchall()
except Exception as e:
print "error in executing with exception: ", e