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

编程入门 行业动态 更新时间:2024-10-26 15:19:11
本文介绍了如何在线程中运行aiohttp服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此aiohttp服务器在线程中的示例失败,并出现 RuntimeError:线程'Thread-1'中没有当前事件循环。错误:

This example of aiohttp server in a thread fails with an RuntimeError: There is no current event loop in thread 'Thread-1'. error:

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服务器?

How to run a aiohttp server in thread?

推荐答案

在主线程中创建处理程序,并在子线程中手动创建事件循环。

Create handler in main thread and manually create an event loop in child thread.

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()

更新

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

Update

For new aiohttp, use the following, thank @Auyer for notification.

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()

更多推荐

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

本文发布于:2023-11-23 10:18:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621089.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   服务器   如何在   aiohttp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!