Asyncio within a thread - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Asyncio within a thread (/thread-8838.html) |
Asyncio within a thread - hollymcr - Mar-09-2018 I'm new to asyncio and I'm trying to understand how to incorporate it into a thread. What I need to do is add a web server with websockets into an existing application. That is, the existing application will continue to function as it already does, but additionally, a web server will run in a separate thread providing access to some of the data from the application via a web browser, and also periodically pushing data to the web browser via web sockets. All the examples I can find seem to assume that the web server is the only thing that the entire application needs to do. I have a very simple test application below, based on the example in the docs as well as the best write-up on asyncio I have found so far. It has a couple of issues:
Am I heading in completely the wrong direction, or am I close? import asyncio import threading from aiohttp import web import time async def wshandler(request): ws = web.WebSocketResponse() await ws.prepare(request) async for msg in ws: if msg.type == web.MsgType.text: x = "Hello, {}".format(msg.data) print(x) await ws.send_str(x) elif msg.type == web.MsgType.binary: await ws.send_bytes(msg.data) elif msg.type == web.MsgType.close: break return ws async def handler(request): name = request.match_info.get('name', "Anonymous") text = "Hello, " + name return web.Response(text=text) async def init(loop): global srv app = web.Application(loop=loop) app.router.add_get('/ws', wshandler) app.router.add_get('/', handler) app.router.add_get('/{name}', handler) srv = await loop.create_server(app.make_handler(), '0.0.0.0', 8080) print("Server started at http://127.0.0.1:8080") return srv def test(loop): loop.run_until_complete(init(loop)) loop.run_forever() loop = asyncio.new_event_loop() t = threading.Thread(target=test,args=(loop,)) try: t.start() while True: print('.', end='', flush=True) time.sleep(1) except KeyboardInterrupt: loop.stop() RE: Asyncio within a thread - wavic - Mar-09-2018 except KeyboardInterrupt: loop.stop() loop.close()Does this work? RE: Asyncio within a thread - hollymcr - Mar-12-2018 (Mar-09-2018, 07:03 PM)wavic Wrote:except KeyboardInterrupt: loop.stop() loop.close()Does this work?
|