如何停止aiohttp服务器在线程中运行?

问题描述 投票:1回答:1

我正在开发UI应用程序(kivy),并尝试实现python AIOHTTP Server的启动和停止按钮。我在另一篇文章中找到了如何在线程中启动aiohttp服务器的示例(UI应用使用主线程)。但是不确定如何停止aiohttp服务器在线程中运行,因为loop.run_forever是一种阻止方法。

提前感谢。

Python 3.7.0aiohttp 3.6.2操作系统:Windows

代码是:

Serverthread.py

import asyncio
from aiohttp import web


def aiohttp_server():
    print("aiohttp_server runner created")

    async def say_hello(request):
        return web.Response(text='Hello, world')

    app = web.Application()
    app.add_routes([web.get('/', say_hello)])
    runner = web.AppRunner(app)
    return runner


def run_server(runner):
    print("Entering run_server")
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(runner.setup())
    site = web.TCPSite(runner, 'localhost', 8080)
    loop.run_until_complete(site.start())
    print("Loop run_forever")
    loop.run_forever()


def stop_server(runner):
    print("Entering stop_server")

App,my-ui.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, NumericProperty

from serverthread import run_server, aiohttp_server
import threading


class ServerAdmin(Widget):
    active_threads = NumericProperty(0)
    t = ObjectProperty(threading.Thread(target=run_server, args=(aiohttp_server(),), daemon=True))

    def start_server(self):
        if self.active_threads == 0:
            print("starting server...")
            self.t.start()
            self.active_threads += 1
            print("Server thread started.")

        else:
            print("Number of active threads: ", str(self.active_threads))

    def stop_server(self):
        print("stopping server...")
        print(f"Check if thread active: {str(self.t.isAlive())}, {self.t.name}")
        pass


class MyUiApp(App):
    def build(self):
        return ServerAdmin()


if __name__ == '__main__':
    MyUiApp().run()

python kivy python-multithreading aiohttp
1个回答
0
投票

分享事件

class ServerAdmin(Widget):
    stop = ObjectProperty(asyncio.Event())
    t = ObjectProperty(threading.Thread(target=run_server, args=(aiohttp_server(),stop ), daemon=True))

    def stop_server(self):
        self.stop.set()


def run_server(runner, stop):
    ...
    print("Loop run_forever")
    # loop.run_forever()
    loop.run_until_complete(stop.wait())
    loop.close()
© www.soinside.com 2019 - 2024. All rights reserved.