J
J
Jekson2021-04-26 13:21:11
Python
Jekson, 2021-04-26 13:21:11

Async code execution error when connecting to redis?

There is a class with basic functionality for making requests to radishes (via aioredis)

class RedisService:
    def __init__(self, r_url) -> str:
        self.redis = r_url

    async def create_connection(self):
        return await aioredis.create_redis(self.redis)

    async def _get(self, key) -> str:
        try:
            return await self.create_connection().get(key, encoding='utf-8')
        finally:
            await self._close()

    async def _set(self, key, value) -> None:
        await self.create_connection().set(key, value)
        await self._close()

    async def _close(self) -> None:
        self.create_connection.close()
        await self._redis.wait_closed()


And a handler to check if it works
@router.post('/perform')
async def index():
    key = 'test'
    value = 'test'
    value = await RedisService(r_url)._set(key, value)
    return {'result': value}


Now when starting the handler, an error occurs
await self.create_connection.set(key, value)
AttributeError: 'coroutine' object has no attribute 'set'


I assume that the reason is that the coroutine should be executed in the
asyncio.run (some coroutine) event loop,

but I can’t catch up on how to fasten it, although this may not be the only thing.

On the docks it looks like this
import asyncio
import aioredis


async def main():
    # Redis client bound to single connection (no auto reconnection).
    redis = await aioredis.create_redis(
        'redis://localhost')
    await redis.set('my-key', 'value')
    val = await redis.get('my-key')
    print(val)

    # gracefully closing underlying connection
    redis.close()
    await redis.wait_closed()

    await redis.wait_closed()

if __name__ == '__main__':
    asyncio.run(main())

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question