我正在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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句