Ich frage mich, ob die Funktion, die websockets verwendet, die "asyncio" enthält, sich nach oben ausbreitet und für immer "async / await" wird ... Ich dachte ich habe es mit meiner eigenen Bibliothek geschafft, also ein Memorandum dieses Teils
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,  #Beispiel-Standardport für Websockets-Server
)
@api.websocket
def reciever(msg):
    print(msg)
api.websocket.run()
Recommended Posts