Python 3.x Can';t停止aiohttp websocket服务器

Python 3.x Can';t停止aiohttp websocket服务器,python-3.x,aiohttp,Python 3.x,Aiohttp,我无法从应用程序中取消我的aiohttp websocket服务器。我想在收到“cancel”字符串时停止服务器并关机 从客户那里。是的,我明白了,我完成了我的协同例程(websocket_handler),但是aiohttp库中有三个协同例程仍在继续工作 当然,我可以在我的共同例程结束时调用asyncio.get\u event\u loop().stop(),但是有没有一种优雅的方法来停止AIOHTP服务器呢 从我的代码中可以看出,我尝试在关闭时使用Application()。append

我无法从应用程序中取消我的aiohttp websocket服务器。我想在收到“cancel”字符串时停止服务器并关机 从客户那里。是的,我明白了,我完成了我的协同例程(websocket_handler),但是aiohttp库中有三个协同例程仍在继续工作

当然,我可以在我的共同例程结束时调用
asyncio.get\u event\u loop().stop()
,但是有没有一种优雅的方法来停止AIOHTP服务器呢

从我的代码中可以看出,我尝试在关闭时使用
Application()。append()
,但失败了

正确的方法是什么

#!/usr/bin/env python #--编码:utf-8-- 导入操作系统 导入异步 输入信号 进口武器

import aiohttp.web
from   aiohttp import ClientConnectionError, WSCloseCode

# This restores the default Ctrl+C signal handler, which just kills the process
#https://stackoverflow.com/questions/27480967/why-does-the-asyncios-event-loop-suppress-the-keyboardinterrupt-on-windows
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

HOST = os.getenv('HOST', 'localhost')
PORT = int(os.getenv('PORT', 8881))

async def testhandle(request):
    #Сопрограмма одрабатывающая http-запрос по адресу "http://127.0.0.1:8881/test"
    print("server: into testhandle()")
    return aiohttp.web.Response(text='Test handle')

async def websocket_handler(request):
    #Сопрограмма одрабатывающая ws-запрос по адресу "http://127.0.0.1:8881"   
    print('Websocket connection starting')
    ws = aiohttp.web.WebSocketResponse()
    await ws.prepare(request)
    request.app['websockets'].add(ws)
    print('Websocket connection ready')
    try:
        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                if msg.data == 'close':
                    print(msg.data) 
                    break    
                else:
                    print(msg.data)
                    await ws.send_str("You said: {}".format(msg.data))
            elif msg.type == aiohttp.WSMsgType.ERROR:
                print('ws connection closed with exception %s' %
                    ws.exception())             
    except (asyncio.CancelledError, ClientConnectionError):   
        pass    # Тут оказываемся когда, клиент отвалился. 
                # В будущем можно тут освобождать ресурсы. 
    finally:
        print('Websocket connection closed')
        request.app['websockets'].discard(ws)
        #pending = asyncio.Task.all_tasks()
        #asyncio.get_event_loop().stop()
    return ws

async def on_shutdown(app):
    for ws in set(app['websockets']):
        await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown')   

def main():
    loop = asyncio.get_event_loop()
    app  = aiohttp.web.Application()
    app['websockets'] = weakref.WeakSet()
    app.on_shutdown.append(on_shutdown)  
    app.add_routes([aiohttp.web.get('/', websocket_handler)])        #, aiohttp.web.get('/test', testhandle)   

    try:
        aiohttp.web.run_app(app, host=HOST, port=PORT, handle_signals=True)
        print("after run_app")
    except Exception as exc:
        print ("in exception")
    finally:
        loop.close()

if __name__ == '__main__':
    main()

关机后,还应执行清理()

app.shutdown()
app.cleanup()