gpt4 book ai didi

python - psycopg2 - 未加密的连接

转载 作者:行者123 更新时间:2023-11-29 13:45:38 26 4
gpt4 key购买 nike

我正在尝试通过 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 block 调整为:

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

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

关于python - psycopg2 - 未加密的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com