我正在使用Python gitlab获取gitlab项目的列表,这些项目以100个为一批的生成器返回。如果一个项目有一个"snow“标签,我想把它添加到一个列表中,这个列表将被转换成一个json对象。下面是我的代码,它可以做到这一点:
gl_prj_list = gl_conn.projects.list(as_list=False)
for p in gl_prj_list:
if "snow" in p.tag_list:
prj = {"id": p.id}
prj["name"] = p.path_with_namespace
gl_data.append(prj)
return json.dumps(gl_data), 200, {'Content-Type': 'text/plain'}所以最终我想要一个可能看起来像这样的结果:( 100个项目中只有2个项目有雪标签)
[{"id": 7077, "name": "robr/snow-cli"}, {"id": 4995, "name": "test/prod-deploy-iaas-spring-starter"}]这一切都很好,但是看起来有点慢。响应时间一般在3.5-5秒之间。由于我将不得不在10-20批中执行此操作,因此我希望改进响应时间。
有没有更好的方法来检查生成器的tag_list属性中的"snow“值并返回结果?
发布于 2019-10-23 23:22:51
假设瓶颈不是应用程序接口调用,您可以使用multiprocessing.Pool()。
from multiprocessing import Pool
def f(p):
if "snow" in p.tag_list:
return {"id":p.id, "name":p.path_with_namespace}
return False
gl_prj_list = gl_conn.projects.list(as_list=False)
with Pool(10) as pool: #10 processes in parallel (change this with the number of cores you have available)
gl_data = pool.map(f, gl_prj_list)
gl_data = [i for i in gl_data if i] #get rid of the False items
json.dumps(gl_data), 200, {'Content-Type': 'text/plain'}如果瓶颈是API调用,并且您想要多次调用API,那么在f()中添加调用并使用相同的技巧。您将并行调用API 10次,而不是顺序调用。
https://stackoverflow.com/questions/58525852
复制相似问题