精神错乱的联系

2024-10-01 17:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过ThreadedConnectionPool同时插入postgres表中的项,但是我一直得到psycopg2.pool.PoolError: trying to put unkeyed connection-不知道为什么会这样。我也尝试过按顺序运行它,但仍然得到相同的错误。在

基本上,代码会从网站的站点地图中获取产品,并将所刮取的项目插入数据库中。在

代码:

class items:

def __init__(self):
    self.conn = ThreadedConnectionPool(10, 100, dbname='postgres', user='xxx', password='xxx', host='xxx')
    self.url = "some url"
    self.session = requests.Session()

def scrape(self, pageNo):
    //some logic
    self.page(pageNo)

// scrapes specified page from sitemap
def page(self, page):
    resp = self.session.get(self.mens+"?page="+str(page)).json()
    products = resp['products']
    ts = []
    for item in products:
        # self.indivProduct(self.url + pageNo)
        t = threading.Thread(target=self.indivProduct, args=self.url + pageNo,))
        ts.append(t)
        t.start()
    for item in ts:
        item.join()

def indivProduct(self, url):

    conn = self.conn.getconn()
    cursor = conn.cursor()

    // Some logic with requests

    try:
        sql = 'insert into "Output" ' \
              '("productID", "brand", "categoryID", "productName", "price", "sizeInfo", "SKU", "URL", "dateInserted", "dateUpdated")' \
              'values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'

        cursor.execute(sql,
                            (.., .., ..,))
        conn.commit()
    except IntegrityError:
        conn.rollback()
        sql = 'insert into "Output" ' \
              '("productID", "brand", "categoryID", "productName", "price", "sizeInfo", "SKU", "URL", "dateInserted", "dateUpdated")' \
              'values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) on conflict ("productID") do update set "dateUpdated" = EXCLUDED."dateUpdated"'
        cursor.execute(sql,
                            (.., .., ..,))
        conn.commit()
    except Exception as e:
        print(e)
        print()
    finally:
        self.conn.putconn()

主要:

^{pr2}$

Tags: selfurlsqldefpageconnitemcursor
1条回答
网友
1楼 · 发布于 2024-10-01 17:28:44

您看到了这个错误,因为您没有将None传递给putconn()函数。 资料来源见: https://github.com/psycopg/psycopg2/blob/master/lib/pool.py

您应该将finally block调整为:

    finally:
        cursor.close()
        self.conn.putconn(conn)

我在强制刷新连接池后遇到错误,并且有一行试图在旧池的连接上调用putconn(conn)。在

相关问题 更多 >

    热门问题