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

bux:

线程中的aiohttp服务器的以下示例失败,并出现RuntimeError: There is no current event loop in thread 'Thread-1'.错误:

import threading
from aiohttp import web


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

    app = web.Application(debug=True)
    app.add_routes([web.get('/', say_hello)])
    web.run_app(app)


t = threading.Thread(target=aiohttp_server)
t.start()

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

Sraw:

handler在主线程中创建,然后在子线程中手动创建事件循环。

import asyncio
import threading
from aiohttp import web


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

    app = web.Application(debug=True)
    app.add_routes([web.get('/', say_hello)])
    handler = app.make_handler()
    return handler


def run_server(handler):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    server = loop.create_server(handler, host='127.0.0.1', port=8089)
    loop.run_until_complete(server)
    loop.run_forever()


t = threading.Thread(target=run_server, args=(aiohttp_server(),))
t.start()

更新资料

对于new aiohttp,请使用以下内容,感谢@Auyer的通知。

import asyncio
import threading
from aiohttp import web


def aiohttp_server():
    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):
    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())
    loop.run_forever()


t = threading.Thread(target=run_server, args=(aiohttp_server(),))
t.start()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Python的线程中运行zeroRpc服务器?

如何在线程中使用 websockets 服务器并正确关闭线程并关闭事件循环?

带有任何功能的服务器类,通过传递服务器生成的值可在线程中运行

如何让python服务器保持活动状态以在线程上运行计划任务?

为什么我的服务器(在线程中运行)没有收到DatagramPackage?

如何在多线程 Unicorn Sinatra 服务器中仅在一个线程中运行函数?

如何在在线服务器上运行laravel php artisan websocket:init命令?

如何在我的 ubuntu 服务器中运行 .cpp?

如何在测试中运行服务器?

如何在xampp服务器中运行MySql?

如何在线程中运行的函数中设置超时

如何在线程中运行python-socketio?

如何在线程中运行Flask SocketIO?

如何在单独的线程中运行 asyncio/websockets 服务器:错误:-> 线程中没有当前事件循环

如何在在线服务器上启动Node JS服务器?

aiohttp:如何从requests.get检索aiohttp服务器中的数据(正文)

同时在python中运行多个服务器(线程)

如何在 Java 中为断开连接的客户端杀死服务器中的线程

套接字服务器在线程中时没有响应

如果在线程中执行,简单的 Winsock 服务器将无法工作

我如何在线程中运行的函数中获取当前线程ID?

如何在python服务器上多线程

服务器如何在Spring框架中为单例对象生成新线程

如何在Java中实现基于线程的UDP服务器?

如何在单独的线程中启动Boost echo服务器

如何在多服务器系统中实现线程安全?

如何在TCP服务器多客户端对话中创建线程

如何在我的网站服务器而不是PC本地服务器中运行node.js

如何在不打开浏览器的情况下在服务器中运行 Slimmerjs?