在x时间后中断while循环,但在相同级别继续for循环

2024-09-29 00:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在使用一些API,在这些API中我必须更新或删除数据。 为了验证我自己,我必须使用一些令牌,这些令牌的有效期大约为10分钟

我的任务需要超过10分钟,所以我不能正常完成我的程序

我解决这个问题的方法是跟踪时间,在9分钟后,我想请求新的令牌,然后继续执行我在for循环中中断的位置

import time

end_time = time.time() + 60*9
while time.time() < end_time:
    for repetition in range(0, 4):
        sw_patcher_ghp = Shopware()
        bearer_token_ghp = sw_patcher_ghp.get_access_token()
        continue
        ##compare both files if skus are matching, grab the data which is needed for patching ruleIds
        for i in range(0, len(all_json)):
            for ii in range(0, len(all_csv)):
                if all_json[i][0] == all_csv[ii][0]:
                    print(sw_patcher_ghp.patch_ruleid(bearer_token_ghp, all_json[i][1], all_csv[ii][1], true_boolean), 'GHP', all_json[i][1])

现在最大的问题是: 我如何请求新令牌,但我还必须能够在我离开的点继续for循环

例如,当我在I=500离开时,我希望在501处收到新代币后开始


Tags: csvintokenapijsonfortimerange
2条回答

好的,我想你的意思是,随时都可以获得一个新的代币,但是你想每9分钟尝试一次:

import time

end_time = time.time() - 1  # force end_time to be invalid at the start
for repetition in range(0, 4):
    ##compare both files if skus are matching, grab the data which is needed for patching ruleIds
    for i in range(0, len(all_json)):
        for ii in range(0, len(all_csv)):
            if all_json[i][0] == all_csv[ii][0]:
                if time.time() > end_time:
                    end_time = time.time() + 60*9
                    sw_patcher_ghp = Shopware()
                    bearer_token_ghp = sw_patcher_ghp.get_access_token()

                print(sw_patcher_ghp.patch_ruleid(bearer_token_ghp, all_json[i][1], all_csv[ii][1], true_boolean), 'GHP', all_json[i][1])

实际上,您不需要while循环。如果9分钟过去了,只需在最里面的循环中请求一个新令牌,然后更新end_time

for repetition in range(0, 4):
    sw_patcher_ghp = Shopware()
    bearer_token_ghp = sw_patcher_ghp.get_access_token()
    
    for i in range(0, len(all_json)):
        for ii in range(0, len(all_csv)):
            if all_json[i][0] == all_csv[ii][0]:
                if end_time >= time.time():
                    #enter code here get new token
                    end_time = time.time()+60*9
                else:
                    print(sw_patcher_ghp.patch_ruleid(bearer_token_ghp, all_json[i][1], all_csv[ii][1], true_boolean), 'GHP', all_json[i][1])

相关问题 更多 >