如何检查循环中的"下一个"字段是否相同?



我通过一个API分页,它使用两种不同的方法-下一个令牌&下一个时间戳。

由于我不知道的原因,有时在调用结束时,下一个令牌将是相同的,这使我陷入无休止的循环。如果我使用下一个时间戳,也会发生同样的情况。

但是,我注意到,如果我使用两者的组合,这是可以避免的。

这是我当前正在运行的循环:

while int(JSONContent['next'][0:10])>unixtime_yesterday:
try:
url='www.website.com?next'+JSONContent['next'][0:10]+'api_key'
JSONContent = requests.request("GET", url, headers=headers).json()
temp_df=json_normalize(JSONContent['data'])
df=df.append(temp_df,ignore_index=True,sort=False)
except ValueError: 
print('There was a JSONDecodeError')

这是JSONContent['next']字段的正常结果。前10个字符是时间戳,后10个字符是另一个标记:'1650377727-3feWs8592va'

我如何检查下一个时间戳是否与当前时间戳相同,以便我可以使用令牌而不是时间戳?

通俗地说,我想做以下事情:

if JSONContent['next'][0:10][current_cycle]=JSONContent['next'][0:10][next_cycle]:
token=JSONContent['next'][11:22][next_cycle]
else:
token=JSONContent['next'][0:10][next_cycle]

如果你只需要"next "在传递到下一个迭代之前,发送另一个请求并检查下一个和下一个之间是否相等。

import time
time_stamp= time.time()
using_token = False
while using_token or int(time_stamp) > unixtime_yesterday:
try:
url = 'www.website.com?next'+JSONContent['next'][0:10]+'api_key'
JSONContent = requests.request("GET", url, headers=headers).json()
next_url = 'www.website.com?next'+JSONContent['next'][0:10]+'api_key'
next_JSONContent = requests.request("GET", url, headers=headers).json()
if JSONContent['next'][0:10] == next_JSONContent['next'][0:10]:
using_token = True
else:
time_stamp = JSONContent['next'][0:10]
using_token = False
temp_df = json_normalize(JSONContent['data'])
df = df.append(temp_df, ignore_index=True, sort=False)
except ValueError:
print('There was a JSONDecodeError')

你也可以初始化using_token为true,但这违反了代码命名规则。

相关内容

最新更新