gpt4 book ai didi

python - 递归使用带有 python 3.5 的请求时出错(GooglePlaces API)

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:12 25 4
gpt4 key购买 nike

我一直遇到一个问题,我尝试发送一个获取请求,如果结果中有下一页标记,它将获取该链接并递归地执行另一个请求,直到结果中没有下一页标记。第一个请求工作正常但是当响应中有下一页 token 并且它尝试执行新请求时结果是无效的响应但是如果我从结果中获取链接并在 postman 或我的浏览器一切正常。我假设它有一些东西可以同时在不同的线程上运行。

使用 Python 的请求的第二个响应:

{'html_attributions': [], 'status': 'INVALID_REQUEST', 'results': []}

这是我的:

import requests 

def getPlaces(location,radius,type, APIKEY):

url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+location+"&radius="+radius+"&type="+type+"&key="+APIKEY

print('Getting results for type ' + type + '...')

r = requests.get(url)

response = r.json()

results = []

if response['status'] == 'ZERO_RESULTS':
print("Did not find results for the type "+type)
else:
print("Results for type "+type)

for result in response['results']:
results.append(result)
print(result)
print('Printing results')
print(results)

if 'next_page_token' in response:
print("There is a next page")
page_token = response['next_page_token']
print(page_token)
next_results = getNextPlace(page_token,APIKEY)
print(next_results)
results.append(next_results)

return results

# Get the rest of the results


def getNextPlace(page_token,APIKEY):

print('...')

next_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+location+'&radius='+radius+'&type='+type+'&pagetoken=' + page_token + '&key=' + APIKEY

print(next_url)
r = requests.get(next_url)
response = r.json()
results = []
print(response)

if response['status'] == 'ZERO_RESULTS':
print("Did not find results")
elif response['status'] == 'INVALID_REQUEST':
print('Invalid response')
else:
for next_result in response['results']:
results.append(next_result)
print(next_result)

if 'next_page_token' in response:
new_page_token = response['next_page_token']
getNext = getNextPlace(new_page_token,APIKEY)
results.append(getNext)

return results

最佳答案

解决了这个问题!如果最后一个请求在 ~2 秒内,Google API 不允许对其 API 进行连续请求。我所做的只是让程序休眠 3 秒并发送请求。现在一切正常

关于python - 递归使用带有 python 3.5 的请求时出错(GooglePlaces API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45747825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com