带Psycopg2的烧瓶数据库池

问题描述

从池中获取连接并为每个请求创建一个新的游标是否会影响性能

@H_404_3@class Query:
    pool = None
    connection = None
    cursor = None
    error = {}

    def __init__(self,pool):
        self.pool = pool
        self.connection = self.pool.get()
        self.cursor = self.connection.cursor()

    def run(self,query,parameters=None):
        try:
            self.execute(query,parameters)
        except (
                psycopg2.errors.AdminShutdown,psycopg2.NotSupportedError,psycopg2.ProgrammingError,psycopg2.DataError,psycopg2.IntegrityError,psycopg2.OperationalError,psycopg2.InterfaceError,psycopg2.InternalError,psycopg2.DatabaseError,Exception
        ) as e:
            try:
                # Memorize error
                if 'execute' not in self.error:
                    self.error.setdefault('execute',[])
                self.error['execute'].append(e)
                # Make new connection and cursor and run the query again
                self.__init__(self.pool)
                self.execute(query,parameters)
            except (
                    psycopg2.errors.AdminShutdown,Exception
            ) as e:
                DatabaseQueryFailed(e)

    def execute(self,parameters=None):
        self.cursor.execute(query,parameters)

    def row(self):
        return self.cursor.rowcount

    def fetch(self):
        return self.cursor.fetchall()

    def close(self):
        self.cursor.close()
        self.pool.put(self.connection)

@H_404_3@@api.route('/hello',methods=['GET'])
@a.token
def hello_route():
    q = Query(current_app.db)
    q.run('''
        SELECT
            prod_article_pub_id as id
        FROM products.articles
        ''')
    fetch = q.fetch()
    q.close()
    del q
    return {'status': 'ok','row': fetch,'method': a.request.method}

还是在启动应用程序时打开游标并将其用于多个请求更好?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)