python - python函数在根据需要打印数据时返回none
问题描述
我有一个如下 python 脚本,它使用谷歌 API 收集一些商店的信息:
import json
import requests
import time
from config import API_KEY, PLACES_ENDPOINT
def getPlaces(lat, lng, radius, keyword, token=None, places=None):
# Building my API call
params = {
'location': str(lat) + ',' + str(lng),
'radius': radius,
'keyword': keyword,
'key': API_KEY
}
if token is not None:
params.update({'pagetoken': token})
r = requests.get(PLACES_ENDPOINT, params=params)
# If its the first time the function is called, then we create the list variable
if places is None:
places = []
for item in r.json()['results']:
# adding element to my list 'places'
places.append(item['name'])
# if there is more results to gather from the next page, call the func again
if 'next_page_token' in r.json():
token = r.json()['next_page_token']
time.sleep(2)
getPlaces(lat, lng, radius, keyword, token, places)
else:
print(json.dumps(places)) # print all the data collected
return json.dumps(places) # return None
为什么返回的 jsonplaces
是None
,而数据显示在 final 中print
?
解决方案
为了解决我的问题,我只需要去掉 else 语句。由于该函数是递归的,因此在结束循环之前它不会继续返回:
import json
import requests
import time
from config import API_KEY, PLACES_ENDPOINT
def getPlaces(lat, lng, radius, keyword, token=None, places=None):
params = {
'location': str(lat) + ',' + str(lng),
'radius': radius,
'keyword': keyword,
'key': API_KEY
}
if token is not None:
params.update({'pagetoken': token})
r = requests.get(PLACES_ENDPOINT, params=params)
# parsing json
if places is None:
places = []
for item in r.json()['results']:
places.append(item['name'])
if 'next_page_token' in r.json():
token = r.json()['next_page_token']
time.sleep(2)
getPlaces(lat, lng, radius, keyword, token, places)
return json.dumps(places)
感谢 Michael Butscher 的提示!
推荐阅读
- c - atomic_inc_return() 是否保证原子返回值?
- android - 我正在运行条形码扫描仪和二维码扫描仪,但在尝试构建到我的设备时出现 XML 重复错误
- python - QuerySet.count() 如何返回非零值但 list(QuerySet.all()) 产生一个空列表?
- css - 引导表 td 不遵守我的宽度设置
- haskell - 无法定义采用 Int 和 Float 的函数
- python - 不同数据大小的 Matplotlib / Seaborn 小提琴图
- javascript - 如何通过在父母上添加点击事件来阅读孩子?
- html - 在反应容器中自动集中固定宽度值项
- symfony - 用户注意事项:未找到必需的@OA\PathItem():symfony 4
- xml - XSLT 从 xml 规则中获取第一个日期