Tidy up asyncio examples.
"source": [
"import asyncio\n",
"\n",
- "import async_timeout\n",
- "\n",
"import redis.asyncio as redis\n",
"\n",
"STOPWORD = \"STOP\"\n",
"\n",
"async def reader(channel: redis.client.PubSub):\n",
" while True:\n",
- " try:\n",
- " async with async_timeout.timeout(1):\n",
" message = await channel.get_message(ignore_subscribe_messages=True)\n",
" if message is not None:\n",
" print(f\"(Reader) Message Received: {message}\")\n",
" if message[\"data\"].decode() == STOPWORD:\n",
" print(\"(Reader) STOP\")\n",
" break\n",
- " await asyncio.sleep(0.01)\n",
- " except asyncio.TimeoutError:\n",
- " pass\n",
"\n",
"r = redis.from_url(\"redis://localhost\")\n",
- "pubsub = r.pubsub()\n",
+ "async with r.pubsub() as pubsub:\n",
" await pubsub.subscribe(\"channel:1\", \"channel:2\")\n",
"\n",
" future = asyncio.create_task(reader(pubsub))\n",
"source": [
"import asyncio\n",
"\n",
- "import async_timeout\n",
- "\n",
"import redis.asyncio as redis\n",
"\n",
"STOPWORD = \"STOP\"\n",
"\n",
"async def reader(channel: redis.client.PubSub):\n",
" while True:\n",
- " try:\n",
- " async with async_timeout.timeout(1):\n",
" message = await channel.get_message(ignore_subscribe_messages=True)\n",
" if message is not None:\n",
" print(f\"(Reader) Message Received: {message}\")\n",
" if message[\"data\"].decode() == STOPWORD:\n",
" print(\"(Reader) STOP\")\n",
" break\n",
- " await asyncio.sleep(0.01)\n",
- " except asyncio.TimeoutError:\n",
- " pass\n",
"\n",
"\n",
"r = await redis.from_url(\"redis://localhost\")\n",
- "pubsub = r.pubsub()\n",
+ "async with r.pubsub() as pubsub:\n",
" await pubsub.psubscribe(\"channel:*\")\n",
"\n",
" future = asyncio.create_task(reader(pubsub))\n",
