如何加快API请求?

cli*_*ere 7 python api

我已经构建了以下用于使用google的地方api获取电话号码的小程序,但它很慢.当我用6个项目进行测试时,它需要从4.86秒到1.99秒,我不确定为什么会发生重大变化.我对API很新,所以我甚至不确定哪些事情可以/不能加速,哪些事情留给服务于API的网络服务器以及我可以改变自己.

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))
Run Code Online (Sandbox Code Playgroud)

Łuk*_*ski 8

您可能希望并行发送请求.Python提供了multiprocessing适合这样的任务的模块.

示例代码:

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))
Run Code Online (Sandbox Code Playgroud)

  • [什么`if __name__ =="__ main __":`do?](http://stackoverflow.com/questions/419163/what-does-if-name-main-do). (2认同)
  • 我的意思不是问,if 中包含的所有内容是什么。像 Pool(5) 和 p.map (2认同)
  • 我会提供一些解释,尽管它可能会帮不上忙,因为它已经为时2.5年了:`with Pool..`在上下文管理器的控制下创建`Pool`对象,这意味着该对象将被销毁程序退出`with`语句范围时调用的清理代码。Pool(5)创建一个具有5个线程的线程池,这些线程都能够独立运行。这意味着您发出的第二个HTTP请求不必等待第一个HTTP请求被返回-因此,您无需一次连续进行5 200ms操作,而是一次完成5 200ms等待。 (2认同)

Joe*_*fer 7

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

文档:请求高级用法 - 会话对象

  • 这使我的速度提高了大约 33%!谢谢!(136s -> 91s,供参考) (3认同)
  • 死链接。尝试提交编辑但编辑队列已满?这是新的[链接](https://requests.readthedocs.io/en/latest/user/advanced/#session-objects)。 (3认同)

Sto*_*ica 6

大多数时间都没有花在计算您的请求上。时间花在与服务器的通信上。那是你无法控制的事情。

但是,您可以使用并行化来加快速度。为每个请求创建一个单独的线程作为开始。

from threading import Thread

def request_search_terms(*args):
    #your logic for a request goes here
    pass

#...

threads = []
for st in searchTerms:
    threads.append (Thread (target=request_search_terms, args=(st,)))
    threads[-1].start()

for t in threads:
    t.join();
Run Code Online (Sandbox Code Playgroud)

然后随着请求数量的增长使用线程池,这将避免重复创建线程的开销。