I wonder if the function using websockets that contains ʻasyncio will spread to the top and become ʻasync / await
forever ... I was thinking I managed to do it with my own library, so a memorandum of that part
--I used a decorator
my_library.py
import websockets
import asyncio
class EntitySpec(object):
def __init__(self, ctx):
self.ctx = ctx
self.uri = "ws://{}:{}".format(
ctx.hostname, ctx.port,
)
def __call__(self, func):
async def stream(func):
async with websockets.connect(self.uri) as ws:
while not ws.closed:
try:
response = await ws.recv()
func(response)
except websockets.exceptions.ConnectionClosedOK:
self.loop.stop()
self.loop = asyncio.get_event_loop()
self.loop.create_task(stream(func))
return stream
def run(self):
self.loop.run_forever()
class Context(object):
def __init__(
self,
hostname='localhost',
port=8765,
):
self.hostname = hostname
self.port = port
self.websocket = EntitySpec(self)
main.py
import my_library
api = my_library.Context(
hostname = 'localhost',
port = 8765, #websockets server sample standard port
)
@api.websocket
def reciever(msg):
print(msg)
api.websocket.run()
Recommended Posts