python 3.7对cosmos db的异步http请求

2024-05-15 16:58:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我想使用Python向cosmosdb发送异步HTTP请求以执行批量插入操作。我曾尝试将多线程与asyncio结合使用来完成这项任务。它已经给了我一个很好的性能,但我相信它肯定可以得到更多的改进,下面是代码:

        try:
            loop = asyncio.new_event_loop()
            return loop.run_until_complete(save(request.json))
        except ValidationException as e:
            return send_error(e)
    async def save(self, users):
        with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
            loop = asyncio.get_event_loop()
            futures = [
                loop.run_in_executor(
                    executor,
                    self.__save_to_cosmos,
                    user
                )
                for user in users
            ]
            result = await asyncio.gather(*futures)
        return result

请注意,“\u save \u to \u cosmos”方法使用python SDK及其同步代码将HTTP请求发送到cosmos DB,因为据我所知cosmos DB SDK不支持异步操作。你知道吗

有谁能建议有没有更好的方法来完成这项任务?你知道吗


Tags: run代码inselfloopeventasynciohttp
1条回答
网友
1楼 · 发布于 2024-05-15 16:58:23

Can anyone suggest if there is a better way to achieve this task?

好吧,很难完美地回答这样的问题。据我所知,我试着和你分享一些想法。根据bulk executor document,cosmosdb只支持.netjava库。因此,您需要自己封装Python的bulk方法。你知道吗

目前,您使用asyncio包,它使用一个事件循环来处理将要处理的内容。一切都在一个进程和一个基于线程在此基础上,我认为您可以使用multiprocessing包来进一步改进效率。拜托请参阅multiprocessingdocument

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine.

据我所知,asyncio让您的任务在事件循环(单进程)中运行,而多进程让您的asyncio任务同时在多个进程上运行,这样您就可以充分利用计算机的容量。你知道吗

请通过link了解这两个线程之间的差异。您可以尝试将asynciomultiprocessing结合起来,请参考以下线程:

1.What kind of problems (if any) would there be combining asyncio with multiprocessing?

2.github:https://github.com/dano/aioprocessing

相关问题 更多 >