PostgreSQL + Python: Close Connection

I created a game server in Python that connects to PostgreSQL db using psycopg2. I saw examples, I saw that when creating a connection to the database, you should close the connection when creating queries, for example, for each client:

#create connection to db
con = psycopg2.connect (database = 'testdb', user = 'janbodnar')
cur = con.cursor ()
#process query
.
.
.
#close connection
con.close ()

Well, when I start my server, I have this:

Inside my class

def __init __ (self):
      #create connection to db
      con = psycopg2.connect (database = 'testdb', user = 'janbodnar')
      cur = con.cursor ()

# to all customers ...
def query(self):
      #process query, for example ...
      cur.execute ("DROP TABLE IF EXISTS Cars")
      #the connection never closes

That is, I use the same connection object for all requests from all clients and never close the connection, it looks better than opening and closing connections for each client, my server seems to work well. do you think about it is it well done? not to do?. Thanks you

+4
source share
3 answers

, . : ? ? ? ? . : psycopg gevent?

. , ( ), db . , . .

- , , . , , .

, http://initd.org/psycopg/docs/pool.html

PS self.con self.cur.

+2

, : max_connections postgres, . .

0

@Michał Niklas self.con self.cur, "".

, .

:

"" , , , :

: client1... "" , ...

def query (self):
       #create connection to db for client1
       con = psycopg2.connect (database = 'testdb', user = 'janbodnar')
       cur = con.cursor ()
       #process query for client1, for example ...
       cur.execute ("DROP TABLE IF EXISTS Cars")
       #close connection for this client
       con.close ()

what do they think about it? it seems better to me. I appreciate the suggestions and support.

0
source

All Articles