Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Update redis to follow the latest spec #6907

Merged
merged 5 commits into from Oct 30, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/6907.doc
@@ -0,0 +1 @@
Updated Redis code examples from the document to follow the latest API.
34 changes: 20 additions & 14 deletions docs/web_advanced.rst
Expand Up @@ -896,20 +896,26 @@ background tasks could be registered as an :attr:`Application.on_startup`
signal handler or :attr:`Application.cleanup_ctx` as shown in the example
below::


async def listen_to_redis(app):
try:
sub = await aioredis.create_redis(('localhost', 6379))
ch, *_ = await sub.subscribe('news')
async for msg in ch.iter(encoding='utf-8'):
# Forward message to all connected websockets:
for ws in app[websockets]:
ws.send_str('{}: {}'.format(ch.name, msg))
except asyncio.CancelledError:
pass
finally:
rapsealk marked this conversation as resolved.
Show resolved Hide resolved
await sub.unsubscribe(ch.name)
await sub.quit()
import redis.asyncio as redis
from aiohttp import web


rapsealk marked this conversation as resolved.
Show resolved Hide resolved
async def listen_to_redis(app: web.Application):
client = redis.from_url('redis://localhost:6379')
pubsub = client.pubsub()
channel = 'news'
await pubsub.subscribe(channel)
while True:
try:
msg = await pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0)
rapsealk marked this conversation as resolved.
Show resolved Hide resolved
if msg is not None:
for ws in app['websockets']:
ws.send_str('{}: {}'.format(channel, msg))
await asyncio.sleep(0.01)
rapsealk marked this conversation as resolved.
Show resolved Hide resolved
except asyncio.CancelledError:
break
await pubsub.unsubscribe(channel)
await pubsub.close()


async def background_tasks(app):
Expand Down