发生异常:在 sql alchemy 1.4 中进行连接查询时 MissingGreenlet

Exception has occurred: MissingGreenlet whe making connection query in sql alchemy 1.4

我正在尝试在 pytest

中使用 SQLAlchemy 1.4.17 进行简单查询
def test_first():
    engine = create_engine(settings.SQLALCHEMY_DATABASE_URI)
    result = engine.execute(text("SELECT email FROM user"))

但收到此错误

Exception has occurred: MissingGreenlet
greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: http://sqlalche.me/e/14/xd2s)
  File "/Users/mattc/Development/inference/server/inference_server/app/tests/test_01_user.py", line 27, in test_first
    result = engine.execute(text("SELECT email FROM user"))

不知道为什么?有什么建议吗?

您正在尝试以与同步连接器相同的方式使用异步连接器包

>>> import sqlalchemy as sa
>>> engine = sa.create_engine('postgresql+asyncpg:///test')
>>> res = engine.execute(sa.text('SELECT * FROM users'))
<stdin>:1: RemovedIn20Warning: The Engine.execute() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the Connection.execute() method of Connection, or in the ORM by the Session.execute() method of Session. (Background on SQLAlchemy 2.0 at: http://sqlalche.me/e/b8d9)
Traceback (most recent call last):
...
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: http://sqlalche.me/e/14/xd2s)

您需要使用同步连接器,例如 psycopg2、pg8000,或者编写异步代码:

import sqlalchemy as sa

import asyncio

from sqlalchemy.ext.asyncio import create_async_engine


async def async_main():
    engine = create_async_engine(
        "postgresql+asyncpg:///test", echo=True,
    )

    async with engine.connect() as conn:

        # select a Result, which will be delivered with buffered
        # results
        result = await conn.execute(sa.text('select email from users'))

        print(result.fetchall())
    await engine.dispose()


asyncio.run(async_main())