在p语言中如何处理两个请求

2024-09-28 03:16:23 发布

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

我有以下代码,从Amazon的API中请求一些内容:

params = {'Operation': 'GetRequesterStatistic', 'Statistic': 'NumberHITsAssignable', 'TimePeriod': 'LifeToDate'}
response = self.conn.make_request(action=None, params=params, path='/', verb='GET')
data['ActiveHITs'] = self.conn._process_response(response).LongValue

params = {'Operation': 'GetRequesterStatistic', 'Statistic': 'NumberAssignmentsPending', 'TimePeriod': 'LifeToDate'}
response = self.conn.make_request(action=None, params=params, path='/', verb='GET')
data['PendingAssignments'] = self.conn._process_response(response).LongValue

每一个请求都需要1s的时间等待Amazon返回数据。我如何同时运行这两个程序,这样(理想情况下)只需要1秒,而不是2秒?在


Tags: pathselfnoneamazonmakeresponserequestaction
1条回答
网友
1楼 · 发布于 2024-09-28 03:16:23

您可以使用^{}来并行化请求:

from multiprocessing import Pool

class Foo:
    def __fetch(self, statistic):
        params = {
            'Operation': 'GetRequesterStatistic',
            'Statistic': statistic,
            'TimePeriod': 'LifeToDate'
        }
        response = self.conn.make_request(
            action=None, params=params, path='/', verb='GET'
        )
        return self.conn._process_response(response).LongValue

    def get_stats(self):
        pool = Pool()
        results = pool.map(self.__fetch, [
            'NumberHITsAssignable', 'NumberAssignmentsPending'
        ])
        data['ActiveHITs'], data['PendingAssignments'] = results

这样可以并行处理任何给定数量的请求。默认情况下,每个核心创建一个worker,您可以通过向Pool传递一个参数来更改该数字。在

相关问题 更多 >

    热门问题