繁体   English   中英

psycopg2-未锁定的连接

[英]psycopg2 - Unkeyed Connection

我正在尝试通过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()

主要:

s = items()
s.scrape(3)

由于将None传递给putconn()函数,因此您会看到此错误。 可以在以下位置查看源代码: https : //github.com/psycopg/psycopg2/blob/master/lib/pool.py

您应该将您的finally块调整为:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM