如何进行 Python 并行 API 请求处理?
How to do Python parallel API request processing?
我正在 Python(Django) 上编写 REST 服务,该服务应该通过 API.
与另一个 REST 服务合并
这里是一些代码和行时间:
connection = statServer("myname", "mypassword")
q1 = connection.getJSONdict("query1") # approximately 15 seconds
q2 = connection.getJSONdict("query2") # approximately 20 seconds
q3 = connection.getJSONdict("query3") # approximately 15 seconds
# my processing approximately 0.01 of second
# merge q1 + q2 + q3
我很清楚每个请求 getJSONdict("query") 实际上除了等待 I/O 之外什么都不做,所以它不消耗处理器时间.
请求是顺序的,因此我可以 运行 它们在不同的线程上。据称我知道 Python 不提供真正的线程,但在我的情况下我等待 I/O 所以我可以做类似线程的事情。
我认为这是 Python 的常见用户案例,如果您处理过类似的任务,请帮助解决我的问题。
我考虑过 Fork/Join 框架或更好的框架将是 ThreadExecutorPull 以从我的 REST 服务中的所有请求中消耗我的请求(并重用线程)。
我自己搞定了
from multiprocessing.pool import Pool, ThreadPool
# ... others imports
# You can dicede here to use processes or threads,
# if you want threads change Pool() to ThreadPool()
pool = Pool()
connection = statServer("myname", "mypassword")
res = pool.map(connection.getJSONdict, ["query1", "query2", "query3"])
print(res)
我正在 Python(Django) 上编写 REST 服务,该服务应该通过 API.
与另一个 REST 服务合并这里是一些代码和行时间:
connection = statServer("myname", "mypassword")
q1 = connection.getJSONdict("query1") # approximately 15 seconds
q2 = connection.getJSONdict("query2") # approximately 20 seconds
q3 = connection.getJSONdict("query3") # approximately 15 seconds
# my processing approximately 0.01 of second
# merge q1 + q2 + q3
我很清楚每个请求 getJSONdict("query") 实际上除了等待 I/O 之外什么都不做,所以它不消耗处理器时间.
请求是顺序的,因此我可以 运行 它们在不同的线程上。据称我知道 Python 不提供真正的线程,但在我的情况下我等待 I/O 所以我可以做类似线程的事情。
我认为这是 Python 的常见用户案例,如果您处理过类似的任务,请帮助解决我的问题。
我考虑过 Fork/Join 框架或更好的框架将是 ThreadExecutorPull 以从我的 REST 服务中的所有请求中消耗我的请求(并重用线程)。
我自己搞定了
from multiprocessing.pool import Pool, ThreadPool
# ... others imports
# You can dicede here to use processes or threads,
# if you want threads change Pool() to ThreadPool()
pool = Pool()
connection = statServer("myname", "mypassword")
res = pool.map(connection.getJSONdict, ["query1", "query2", "query3"])
print(res)