我正在运行下面的代码。我试图通过创建可以在aiohttp View 对象中使用的全局连接池对象,将aioredis与aiohttp一起使用。但是load_redis函数出错。我什至不确定这是否是将aioredis与aiohttp结合使用的正确方法。

#!/usr/bin/env python

import asyncio
import uvloop
from aiohttp import web
from settings import SERVER_IP, SERVER_PORT, REDIS_HOST, REDIS_PORT
import aiohttp_jinja2
import jinja2
import aioredis





asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
app = web.Application()
aiohttp_jinja2.setup(app,
    loader=jinja2.FileSystemLoader('templates'))

REDIS_CONNECTION_POOL = None
async def load_redis():
    global REDIS_CONNECTION_POOL
    REDIS_CONNECTION_POOL = await aioredis.create_pool(
        (REDIS_HOST, REDIS_PORT),
        minsize=5, maxsize=10,
        loop=loop)
    await REDIS_CONNECTION_POOL.execute('set', 'current_code', '00000')
loop.run_until_complete(load_redis())


#prevent import errors
from routes import setup_routes
setup_routes(app)
web.run_app(app, host=SERVER_IP, port=SERVER_PORT)

这是运行此命令时看到的错误消息:
Traceback (most recent call last):
  File "server.py", line 29, in <module>
    loop.run_until_complete(load_redis())
  File "uvloop/loop.pyx", line 1203, in uvloop.loop.Loop.run_until_complete (uvloop/loop.c:25632)
  File "server.py", line 28, in load_redis
    await REDIS_CONNECTION_POOL.execute('set', 'current_code', '00000')
AttributeError: 'RedisPool' object has no attribute 'execute'
Task was destroyed but it is pending!
task: <Task pending coro=<RedisPool._do_close() running at /Users/brian/.pyenv/versions/3.6.0/lib/python3.6/site-packages/aioredis/pool.py:117> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x10bb94b58>()]>>

最佳答案

您不需要使用全局变量,而是使用on_startup / on_cleanup信号,如下所示:http://aiohttp.readthedocs.io/en/stable/web.html#background-tasks

另请参阅https://github.com/aio-libs/aiohttp/issues/2131

关于python - aioredis + aiohttp连接池的正确用法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45134300/

10-12 18:23