Код: Выделить всё
def page_helper(req, timeout=5, page=1, **kwargs):
print(f"Page {page}", end="\r")
try:
response = req(params={**kwargs, "page": page})
response = response.json()
except Exception as e:
status = response.status_code
if status == "429":
print(f"Rate limited. Waiting {timeout} seconds.")
time.sleep(timeout)
yield from page_helper(req, page=page, **kwargs)
else:
raise e
else:
if len(response) == kwargs["limit"]:
yield from page_helper(req, page=page + 1, **kwargs)
yield response
Код: Выделить всё
batches = page_helper()
# get insert and updates per batch
for i, batch in enumerate(batches):
print(f"Batch {i + 1}", end="\r")
insert_batch = []
update_batch = []
# ... process batch
Я пытался проверить генератор, вызвав next, и ожидаю, что он вернет только один пакет. Однако он немедленно запускает полные итерации:
Код: Выделить всё
next(batches) # --> Performs full iteration
next(batches)
next(batches)
next(batches)
Подробнее здесь: https://stackoverflow.com/questions/791 ... ext-method
Мобильная версия