0

I have been learning some examples here from psycopg3 https://www.psycopg.org/psycopg3/docs/advanced/async.html#with-async-connections , but none of them are working for me. First by running the examples the python interpreter complains that async can only can be called inside a function. I solved this by adding an async function, however when calling that function I get that the coroutine was never awaited:

import psycopg
from config import config
from pathlib import WindowsPath
from psycopg import sql


async def main():
    conn = await psycopg.AsyncConnection(f'postgresql://{config.USER_PG}:{config.PASS_PG}@{config.HOST_PG}:{config.PORT_PG}/{config.DATABASE_PG}').connect()

    p = WindowsPath(r'.\data\product_version.csv')

    async with conn:
        if p.exists():
            with p.open() as f:
                # define columns    
                columns = list(next(p).rstrip().lower().split(','))
                print(columns)
                # Open a cursor to perform database operations
                async with conn.cursor() as cur:
                    # empty table contents before write
                    await cur.execute(sql.SQL("TRUNCATE TABLE {} RESTART IDENTITY").format(sql.Identifier('product_version_map')))
                    # write file content
                    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')


main()


c:\Users\45291029\Documents\evergreen\project\backend\src\write_map_versions.py:31: RuntimeWarning: coroutine 'main' was never awaited
  main()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

What am i doing wrong here ? Thanks. I am beginner into async programming.

moth
  • 1,833
  • 12
  • 29
  • 1
    Don't call `main` at the bottom of your module, pass it's return value to `asyncio.run` instead `asyncio.run(main())`. See https://docs.python.org/3/library/asyncio-runner.html#asyncio.run for more. – FiddleStix Feb 21 '23 at 10:26

0 Answers0