如何加速API请求?

2024-03-28 14:12:56 发布

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

我已经构建了以下使用google的place api获取电话号码的小程序,但是它非常慢。当我用6个项目进行测试时,需要4.86秒到1.99秒的时间,我不确定为什么时间会有显著的变化。我对API还不太熟悉,所以我甚至不知道什么样的东西可以/不能加速,什么样的东西留给了为API提供服务的webserver,什么样的东西可以改变我自己。

import requests,json,time
searchTerms = input("input places separated by comma")

start_time = time.time() #timer
searchTerms = searchTerms.split(',')
for i in searchTerms:
    r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY')
    a = r1.json()
    pid = a['results'][0]['place_id']
    r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY')
    b = r2.json()
    phone = b['result']['formatted_phone_number']
    name = b['result']['name']
    website = b['result']['website']
    print(phone+' '+name+' '+website)

print("--- %s seconds ---" % (time.time() - start_time))

Tags: nameapijsoninputtime时间phoneplace
3条回答

这是客户端和服务器之间的延迟问题,除非使用多个服务器位置(客户端附近的服务器正在获取请求),否则您无法以这种方式更改任何内容。

在性能方面,您可以构建一个可以同时处理多个请求的多威胁系统。

您可能希望并行发送请求。Python提供了适合于此类任务的^{}模块。

示例代码:

from multiprocessing import Pool

def get_data(i):
    r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query='+ i +'&key=MY_KEY')
    a = r1.json()
    pid = a['results'][0]['place_id']
    r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+pid+'&key=MY_KEY')
    b = r2.json()
    phone = b['result']['formatted_phone_number']
    name = b['result']['name']
    website = b['result']['website']
    return ' '.join((phone, name, website))

if __name__ == '__main__':
    terms = input("input places separated by comma").split(",")
    with Pool(5) as p:
        print(p.map(get_data, terms))

使用会话启用持久的HTTP连接(这样就不必每次都建立新连接)

文件:Requests Advanced Usage - Session Objects

相关问题 更多 >