Skip to content

Instantly share code, notes, and snippets.

@dhaninugraha
Last active December 13, 2023 13:11
Show Gist options
  • Select an option

  • Save dhaninugraha/395fcc339fcea17d265a2a9901659b7b to your computer and use it in GitHub Desktop.

Select an option

Save dhaninugraha/395fcc339fcea17d265a2a9901659b7b to your computer and use it in GitHub Desktop.
python, redis - live lucky draw
import redis
conn = redis.StrictRedis.from_url("redis://localhost:6379/0")
set_name = "set-containing-elements-to-draw"
def draw(conn, set_name, how_many=1):
import time
while True:
try:
# continuously print available tickets
print(f"\r{conn.srandmember(set_name)}", end="")
time.sleep(0.05)
except KeyboardInterrupt: # Ctrl-C to stop printing and draw winners
drawn = conn.spop(set_name, count=how_many) # randomly draw multiple tickets at once
first_line = True
prefix = "\r"
for i, elem in enumerate(drawn): # print winners line-by-line, just for show
num = f"#{i + 1}"
print(f"{prefix}Drawn {num:>4}: {elem}")
if first_line:
first_line = False
prefix = ""
break
print(f"\nTickets remaining: {conn.scard(set_name)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment