python并發(fā)調(diào)用接口怎么實(shí)現(xiàn)

小億
298
2023-10-27 01:45:29

在Python中,可以使用多線程或者多進(jìn)程來(lái)實(shí)現(xiàn)并發(fā)調(diào)用接口。

  1. 使用多線程實(shí)現(xiàn)并發(fā)調(diào)用接口:
import threading
import requests

def call_api(url):
    response = requests.get(url)
    print(response.json())

urls = ["http://api.example.com/endpoint1", "http://api.example.com/endpoint2", "http://api.example.com/endpoint3"]

threads = []
for url in urls:
    t = threading.Thread(target=call_api, args=(url,))
    t.start()
    threads.append(t)

for t in threads:
    t.join()
  1. 使用多進(jìn)程實(shí)現(xiàn)并發(fā)調(diào)用接口:
import multiprocessing
import requests

def call_api(url):
    response = requests.get(url)
    print(response.json())

urls = ["http://api.example.com/endpoint1", "http://api.example.com/endpoint2", "http://api.example.com/endpoint3"]

processes = []
for url in urls:
    p = multiprocessing.Process(target=call_api, args=(url,))
    p.start()
    processes.append(p)

for p in processes:
    p.join()

無(wú)論使用多線程還是多進(jìn)程,都可以實(shí)現(xiàn)并發(fā)調(diào)用接口,加快執(zhí)行速度。需要注意的是,并發(fā)調(diào)用接口可能會(huì)對(duì)接口服務(wù)器造成較大負(fù)擔(dān),所以在實(shí)際使用中需要根據(jù)接口服務(wù)器的性能和需求做出合理的調(diào)整。

0