异步aioredis连接时报错TypeError: duplicate base class TimeoutError问题
版本
python3.11版本,aioredis 2.0.1版本,redis 7.x版本
redis.conf配置文件
daemonize yes
bind 0.0.0.0
port 6379
protected-mode no
代码
from fastapi import FastAPI
import aioredis
app = FastAPI()
@app.on_event('startup')
async def startup_event():
# 线程池
app.state.redis_client = aioredis.from_url('redis://xxx.xxx.xxx.xx/0',encoding="utf-8", decode_responses=True)
@app.on_event('shutdown')
async def shutdown_event():
await app.state.redis_client.close()
@app.get('/index')
async def index():
key = 'liuwei'
# 设置缓存
await app.state.redis_client.set(key, '123456')
# 读取
result = await app.state.redis_client.get(key)
print(result)
return {'msg': 'ok'}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app='main:app', host='0.0.0.0', port=8001, reload=True)
报错
File "f:\all_django_project\pyscript_demo\main.py", line 2, in <module>
import aioredis
File "F:\all_django_project\pyscript_demo\fast_api_env\Lib\site-packages\aioredis\__init__.py", line 1, in <module>
from aioredis.client import Redis, StrictRedis
File "F:\all_django_project\pyscript_demo\fast_api_env\Lib\site-packages\aioredis\client.py", line 32, in <module>
from aioredis.connection import (
File "F:\all_django_project\pyscript_demo\fast_api_env\Lib\site-packages\aioredis\connection.py", line 33, in <module>
from .exceptions import (
File "F:\all_django_project\pyscript_demo\fast_api_env\Lib\site-packages\aioredis\exceptions.py", line 14, in <module>
class TimeoutError(asyncio.TimeoutError, builtins.TimeoutError, RedisError):
TypeError: duplicate base class TimeoutError
定位分析
File "F:\all_django_project\pyscript_demo\fast_api_env\Lib\site-packages\aioredis\exceptions.py", line 14, in <module>
class TimeoutError(asyncio.TimeoutError, builtins.TimeoutError, RedisError):
TypeError: duplicate base class TimeoutError
启动连接时会报一个TypeError: duplicate base class TimeoutError的错误
问了Copilot,说是兼容性问题,在 Python3.11 中,asyncio.TimeoutError 被移动到了 asyncio.exceptions 模块中,而 aioredis 库没有及时更新以适应这个变化。
所以我们找到aioredis目录下的exceptions.py文件,定位到14行代码
class TimeoutError(asyncio.TimeoutError, builtins.TimeoutError, RedisError):
pass
所以我们修改为如下代码,即可运行
class TimeoutError(asyncio.exceptions.TimeoutError, RedisError):
pass
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!