【发布时间】:2023-02-22 00:11:27
【问题描述】:
我有一个将 csv 文件复制到数据库的功能。我正在尝试异步执行此操作:
import psycopg
from config import config
from pathlib import WindowsPath
from psycopg import sql
import asyncio
async def main():
conn = await psycopg.AsyncConnection.connect(f'postgresql://{config.USER_PG}:{config.PASS_PG}@{config.HOST_PG}:{config.PORT_PG}/{config.DATABASE_PG}')
p = WindowsPath(r'.\data\product_version.csv')
async with conn:
if p.exists():
with p.open(encoding='utf-8-sig') as f:
columns = list(next(f).strip().lower().split(','))
async with conn.cursor() as cur:
await cur.execute(sql.SQL("TRUNCATE TABLE {} RESTART IDENTITY CASCADE").format(sql.Identifier('product_version_map')))
async with cur.copy(sql.SQL("COPY {} ({}) FROM STDIN WITH CSV").format(sql.Identifier('product_version_map'),sql.SQL(', ').join(map(sql.Identifier, columns)))) as copy:
while data := await f.read():
await copy.write(data)
else:
print(f'You need the product_version file')
if __name__=='__main__':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
但我收到此错误:
psycopg.errors.QueryCanceled: COPY from stdin failed: error from Python: TypeError - object str can't be used in 'await' expression
f 这里有类字符串,它是文件的行。错误来自这一行:
while data := await f.read():
这是我在构建此代码时所指的文档:
https://www.psycopg.org/psycopg3/docs/basic/copy.html#asynchronous-copy-support
【问题讨论】:
标签: python asynchronous python-asyncio psycopg2 psycopg3