首页 > 解决方案 > 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

为什么返回的 jsonplacesNone,而数据显示在 final 中print

标签: pythonjsonfunctiongoogle-apireturn

解决方案


为了解决我的问题,我只需要去掉 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 的提示!


推荐阅读