Use secrets for websocket server

This commit is contained in:
Brandon Thomas
2021-03-03 03:46:32 -05:00
parent ae6eda6036
commit d949d71eee
4 changed files with 22 additions and 64 deletions
+5 -62
View File
@@ -4,57 +4,9 @@ import aioredis
import asyncio
import redis
import sys
import toml
import websockets
#redis_client = redis.Redis(host='localhost', port=6379, db=0)
# Redis pubsub (blocking)
"""
pool = redis.ConnectionPool(host='localhost', port=6379, password='', db=0)
redis_pool = redis.StrictRedis(connection_pool=pool)
pubsub = redis_pool.pubsub()
pubsub.subscribe('testing')
pubsub.subscribe('foo')
#for message in pubsub.listen():
# if message['data'] == 'exit':
# sys.exit()
# print(message)
"""
# Single request/response websocket
"""
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
start_server = websockets.serve(hello, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
"""
# Infinitely publishing websocket server:
"""
async def time(websocket, path):
while True:
now = datetime.datetime.utcnow().isoformat() + "Z"
await websocket.send(now)
await asyncio.sleep(random.random() * 3)
start_server = websockets.serve(time, "127.0.0.1", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
"""
from aioredis.pubsub import Receiver
from aioredis.abc import AbcChannel
@@ -64,6 +16,8 @@ CHANNELS = [
'testing',
]
print('reading secrets', flush=True)
SECRETS = toml.load("secrets.toml")
print('defining server', flush=True)
@@ -91,26 +45,15 @@ async def server(websocket, path):
asyncio.ensure_future(reader(mpsc))
redis = await aioredis.create_redis_pool('redis://localhost')
redis = await aioredis.create_redis_pool(SECRETS['redis_url'])
#await redis.subscribe(mpsc.channel('channel:1'), mpsc.channel('channel:testing'), mpsc.channel('testing'))
channels = [mpsc.channel(ch) for ch in CHANNELS]
await redis.subscribe(*channels)
print('starting websocket server', flush=True)
try:
while True:
# Receive data from "the outside world"
#message = await websocket.recv()
# Feed this data to the PUBLISH co-routine
#await publish_to_redis(message, path)
#print('sending ping', flush=True)
#await websocket.send("Websocket ping")
# TODO: Do we need to ping to keepalive?
if not queue.empty():
msg = queue.get_nowait() # TODO THROWS EXCEPTION IF EMPTY (data race?)