创新互联Python教程:python中requests如何优化接口调用
使用python进行网络编程时,经常使用requests模块进行http接口调用。

1、如果只是很少的接口调用,使用传统的requests.post()或者requests.get()就能满足要求。
但是,如果涉及多次界面调用,可能会遇到程序执行时间长的效率问题。
2、为了提高程序执行效率,降低服务器压力,可以使用长连接,节省频繁的tcp连接握手和挥手过程。
实例
def keep_alive():
"""
实例化一个长连接对象
:return:
"""
s = requests.Session()
return s
def q_inst(func, obj_id='host', field='bk_host_innerip', value=''):
headers = {"Content-Type": "application/json"}
data = {
"bk_obj_id": obj_id,
"bk_supplier_account": "0",
"page": {
"start": 0,
"limit": 10
},
"condition": {
obj_id: [{
"field": field,
"operator": "$eq",
"value": value
}]
}
}
res_p = func.post('https://***.***.***/api/c/compapi/v2/cc/search_inst/', data = data, headers = headers)
return res_p
if __name__ == '__main__':
s = keep_alive()
for in range(4001):
res = q_inst(s, value='10.1.1.1')
#################output##########################
查询蓝鲸接口共耗时:0:03:21.099682以上就是python中requests优化接口调用的方法,希望对大家有所帮助。更多Python学习指路:创新互联python教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
标题名称:创新互联Python教程:python中requests如何优化接口调用
文章URL:http://www.jxjierui.cn/article/dpjogoi.html


咨询
建站咨询
