zoukankan      html  css  js  c++  java
  • nest_asyncio出现错误

    Sanic项目做测试,运行 `pytest` 时报了这个错:`RuntimeError: Cannot run the event loop while another loop is running`

    代码如下:

    import pytest
    from models.nezha import get_room_name
    
    
    @pytest.mark.asyncio
    async def test_get_room_name():
    name = await get_room_name('a', 'b')
    assert name == 'b'
    # models/nezha.py
    
    
    async def data_from_cache_or_http(
    data_key: str, etag_key: str, url: str, renew: bool
    ) -> dict:
    ...
    
    async def rooms_from_cache_or_http(
    community: str, renew: bool = False
    ) -> dict:
    data_key, etag_key = ROOMS_CACHED_KEY, ROOMS_ETAG_CACHED_KEY
    url = HOST + f'/room-names/?community={community}'
    return await data_from_cache_or_http(data_key, etag_key, url, renew)
    
    
    async def get_room_name(community: str, slug: str) -> str:
    """获取小区slug和房间slug对应的房号"""
    if community and slug:
    rooms = await rooms_from_cache_or_http(community)
    return rooms.get(slug, {}).get('name')
    return ''
    

      

    原因:。。。google一搜就知道了,或者看这个:https://github.com/erdewit/nest_asyncio

    解决:`pip install nest_asyncio`, 然后添加`import nest_asyncio; nest_asyncio.apply()`

    修改后的test文件内容如下:

    import nest_asyncio
    import pytest
    
    from models.nezha import get_room_name
    
    nest_asyncio.apply()
    
    
    @pytest.mark.asyncio
    async def test_get_room_name():
    name = await get_room_name('a', 'b')
    assert name == 'b'
    

      


    然后运行pytest时,却又报了这个错误:

    ValueError: Can't patch loop of type <class 'uvloop.Loop'>

    原因:nest_asyncio不支持uvloop

    解决:`pip uninstall uvloop`

  • 相关阅读:
    mysql主从复制配置
    mysql三种修改密码的方式
    mysqldump数据库备份与恢复
    mysql多实例安装
    线性回归与梯度下降法——原理与实现
    K-Means聚类算法原理
    EFcodeFirst+T4=操纵任意数据库
    涨姿势UWP源码——IsolatedStorage
    记一次Project插件开发
    基于Nodejs生态圈的TypeScript+React开发入门教程
  • 原文地址:https://www.cnblogs.com/rianley/p/14790675.html
Copyright © 2011-2022 走看看