首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在sql alchemy 1.4中进行连接查询时出现异常: MissingGreenlet

在sql alchemy 1.4中进行连接查询时出现异常: MissingGreenlet
EN

Stack Overflow用户
提问于 2021-06-09 13:00:38
回答 1查看 1.4K关注 0票数 1

我正尝试在pytest中使用SQLAlchemy 1.4.17执行一个简单的查询

代码语言:javascript
运行
复制
def test_first():
    engine = create_engine(settings.SQLALCHEMY_DATABASE_URI)
    result = engine.execute(text("SELECT email FROM user"))

但是我得到了这个错误

代码语言:javascript
运行
复制
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"))

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-09 15:07:53

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

代码语言:javascript
运行
复制
>>> 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,或者编写异步代码:

代码语言:javascript
运行
复制
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())
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67897872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档