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`

  • 相关阅读:
    redis要注意的一些知识
    redis数据类型及常用命令使用
    基于zookeeper的分布式锁
    基于redis的分布式锁
    基于数据库的分布式锁
    数据库的4中隔离级别
    远程调用历史及代码编写demo
    数据库的ACID跟事务隔离级别
    JAVA8 十大新特性详解
    java8 :: 用法 (JDK8 双冒号用法)
  • 原文地址:https://www.cnblogs.com/rianley/p/14790675.html
Copyright © 2011-2022 走看看