gpt4 book ai didi

python - 处理 aiohttp 中的客户端过早断开连接

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:36 25 4
gpt4 key购买 nike

我目前正在测试 aiohttp,但以下代码有问题:

async def index(request: web.Request) -> web.StreamResponse:
response = web.StreamResponse(headers={'content-type': 'text/plain'})
await response.prepare(request)
for i in range(1000000):
try:
response.write(b'test response')
await response.drain()
except concurrent.futures.CancelledError:
print('Remote connection closed... Cleaning up...')
# Do cleanup process here?
raise

return response

现在我通过以下curl 请求尝试一下:

curl -v http://127.0.0.1:8080

然后我按 Ctrl-C 使curl 断开连接并停止下载响应。

在 aiohttp Web 服务器的控制台日志中,我得到很多以下内容:

2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception.
2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception.
2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception.
2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception.
2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception.

这一直循环,我无法使用 Ctrl-C 终止服务器。我必须用 kill -KILL 来杀死它才能完全终止它。看来客户端套接字断开连接是默默处理的。我想消除由 asyncio.selector_events._SelectorSocketTransport.write() 引发的上述警告。我可以通过设置适当的记录器级别来使其静音,但这不是我想要的。另外,当客户端连接终止时,我想要执行很多清理过程。我查看了 aiohttp 代码,似乎没有任何可以连接来处理它的处理程序或信号。理想情况下,我希望能够在客户端连接关闭时进行一些清理。

在 Django 中,我可以通过使用 StreamingHttpResponse 类创建自定义 SelfCleaningStream 类来实现此目的。自定义 SelfCleaningStream 类在 close() 方法中处理清理工作,该方法在客户端连接关闭时由 Django 调用。

最佳答案

感谢您的报告。这是 aiohttp 中的一个错误,我已提交 issue

关于python - 处理 aiohttp 中的客户端过早断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47175297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com