Skip to content

Instantly share code, notes, and snippets.

@leonh
Last active September 18, 2019 13:18
Show Gist options
  • Save leonh/f2fa9e8adca48dcca6b52e525a2f441f to your computer and use it in GitHub Desktop.
Save leonh/f2fa9e8adca48dcca6b52e525a2f441f to your computer and use it in GitHub Desktop.
import asyncio
import aioredis
async def add_new_win(pool, winner):
# Creating tasks doesn't schedule them
# so you can create multiple and then
# schedule them all in one go using `gather`
task1 = pool.zincrby('wins_counter', 1, winner)
task2 = pool.incr('total_games_played')
await asyncio.gather(task1, task2)
async def main():
# Connect to Redis
pool = await aioredis.create_redis_pool(('localhost', 6379))
# Tail the event stream
last_id = '$'
while True:
events = await pool.xread(['wins_stream'], latest_ids=[last_id],
timeout=0, count=10)
tasks = []
for _, e_id, e in events:
winner = e[b'winner']
# Again we don't actually schedule any task,
# and instead just prepare them
tasks.append(add_new_win(pool, winner))
last_id = e_id
# Notice the spread operator (`*tasks`), it
# allows using a single list as multiple arguments
# to a function call.
await asyncio.gather(*tasks)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment