[英]How to share an aiohttp.ClientSession() between processes?
I'm trying to create a shared resource in which I can use an aiohttp.ClientSession() object to fetch certain data.我正在尝试创建一个共享资源,我可以在其中使用 aiohttp.ClientSession() object 来获取某些数据。 This allows me to use parallelization to speed up the actual calculations.这允许我使用并行化来加速实际计算。
However, when I try to create a manager in which I use aiohttp.ClientSession, an error is raised: TypeError: no default __reduce__ due to non-trivial __cinit__
.但是,当我尝试创建使用 aiohttp.ClientSession 的管理器时,会引发错误: TypeError: no default __reduce__ due to non-trivial __cinit__
。
I'm not sure what is going on and perhaps someone would be able to help me out on what this error means and how I could actually initialize a manager that used an aiohttp.ClientSession.我不确定发生了什么,也许有人可以帮助我了解此错误的含义以及我如何实际初始化使用 aiohttp.ClientSession 的管理器。
import asyncio
import aiohttp
# import nest_asyncio
from multiprocessing.managers import BaseManager
class Session:
def __init__(self, loop):
asyncio.set_event_loop(loop)
self.session = aiohttp.ClientSession()
class MyManager(BaseManager):
pass
# nest_asyncio.apply()
MyManager.register('Session', Session)
loop = asyncio.get_event_loop()
with MyManager() as manager:
session = manager.Session(loop)
As a fallback solution, I could use requests, which seems to have no problems when registered in a BaseManager.作为备用解决方案,我可以使用请求,在 BaseManager 中注册时似乎没有问题。 However, this would seriously bottleneck my process, as I have a fairly large workload running over 60+ parallel processes in which each data call takes a fairly long time to complete.但是,这将严重阻碍我的流程,因为我有相当大的工作负载运行 60 多个并行进程,其中每个数据调用都需要相当长的时间才能完成。
import requests
from multiprocessing.managers import BaseManager
class Session:
def __init__(self):
self.session = requests.Session()
class MyManager(BaseManager):
pass
MyManager.register('Session', Session)
with MyManager() as manager:
session = manager.Session()
I hope someone can help me out and many thanks in advance!我希望有人可以帮助我,并提前非常感谢!
Thanks Sraw!谢谢斯劳! Based on your suggestion I managed to create a manager without errors!根据您的建议,我设法创建了一个没有错误的经理! According to the asyncio documentation , a convent and preferred way to create a loop is by simply calling asyncio.run()
.根据asyncio 文档,创建循环的一种修道院和首选方法是简单地调用asyncio.run()
。
import asyncio
import aiohttp
from multiprocessing.managers import BaseManager
class Session:
def __init__(self, beta_engine=False):
process = self._init_session()
asyncio.run(process)
async def _init_session(self):
self.session = aiohttp.ClientSession()
class MyManager(BaseManager):
pass
MyManager.register('Session', Session)
with MyManager() as manager:
session = manager.Session()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.