我正在编写一个我日常互动的Rest API的包装器。当您对具有许多结果的事物发出请求时,它会对它们进行分页。我试图编写一个函数来优雅地解析数据并遇到意想不到的事情 - 如果我尝试在同一个应用程序或IPython会话中重用这个函数,它会将第二个请求的结果堆叠在第一个请求的结果。这是代码:
class RestAPIWrapper(object):
def __init__(self, url=url, acct=acct, token=token):
self.url = url
self._session = requests.Session()
self._session.mount('https://', HTTPAdapter(max_retries=5))
self._session.headers.update({'Accept': 'application/json', 'Content-Type': 'application/json'})
self._session.auth = (acct, token)
def search_api_broken(self, query, page=1, results=[]):
r = self._session.get('{0}/search.json?page={1}&query={2}'.format(self.url, page, query))
response = r.json()
results.extend(response['results'])
#returns a dictionary that has these keys: ['results', 'next_page', 'previous_page']
if response['next_page'] is not None:
results = self.search_api_broken(query, page=page+1, results=results)
return results
def search_api_works(self, query, page=1, results=[]):
if page == 1:
results = []
r = self._session.get('{0}/search.json?page={1}&query={2}&sort_by={3}&sort_order={4}'.format(self.base_url, page, quote(query), sort_by, sort_order))
response = r.json()
results.extend(response['results'])
#returns a dictionary that has these keys: ['results', 'next_page', 'previous_page']
if response['next_page'] is not None:
results = self.search_api_wroks(query, page=page+1, results=results)
return results
换句话说,如果我这样调用方法:
my_api_wrapper = RestAPIWrapper()
#query should return 320 results, #query2 should return 140 results
data = my_api_wrapper.search_api_broken(query)
len(data)
#outputs 320
more_data = my_api_wrapper.search_api_broken(query2)
len(more_data)
#outputs 460
第二种方法的输出包括第一种方法。为什么这样做是因为我将results = []
放在函数定义中?我在调用方法时没有指定它,所以它应该默认为空列表,对吧?
答案 0 :(得分:0)
在“search_api_broken”中,“结果”中的先前内容不明确。