Python 发生异常:在sql alchemy 1.4中进行连接查询时缺少Greenlet

Python 发生异常:在sql alchemy 1.4中进行连接查询时缺少Greenlet,python,sqlalchemy,Python,Sqlalchemy,我试图从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_

我试图从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)

谢谢你的回答。奇怪的是,为什么需要
引擎.dispose()
?不应自动处理,因为它与
async with
引擎创建语句不在
async with engine.connect()语句的范围内。
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())