PostgreSQL连接应该在Python Web应用程序中合并,还是每个请求创建一个新连接?

sky*_*ler 7 python postgresql web-applications psycopg2 flask

我正在用Python构建一个Web应用程序(使用Flask).我不打算使用SQLAlchemy或类似的ORM系统,而是直接使用Psycopg2.

我应该为每个新请求打开一个新的数据库连接(并随后关闭它)吗?或者我应该使用什么来汇集这些连接?

Mar*_*son 10

PgBouncer对应用程序和服务器非常简洁透明.

我们已经在生产中使用PgBouncer 2年而没有一个问题.这是一个非常棒的PostgreSQL连接池.

http://wiki.postgresql.org/wiki/PgBouncer


Sne*_*mar 6

是的,连接池会有所帮助,但是是的,您必须根据数据库上的负载找出实时连接或池大小的正确数字。

    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
Run Code Online (Sandbox Code Playgroud)