Search code examples
pythonpython-3.xfor-loopwhile-loopshopware

Break while loop after x amount of time but continue for loop at the same level


Currently I am working with some apis, in which I have to update or delete data. To authenticate myself, I have to use some tokens, which are valid for like 10mins.

My tasks need more than 10minutes, so I can not finish my program properly.

My solution for this problem would be to track the time and after 9mins, I want to request the new token and keep going exactly where I left off in my for loop.

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])

Now the big problem is: How can I request the new token, but I also have to be able to continue the for loop at the point I have left

E.g when I left at i = 500, I want to start after I have received the new tokens at 501


Solution

  • You don't need a while loop really. Just request for a new token within your innermost loop if 9 minutes have passed and update 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])