to explain the process step by step, I take tokens from the def producttoken(): function and delete each line in the list.csv with the help of the api in the def product_delete(product_id): function with the for loop. But in case the token expired, I want to renew the token again, but if I run the token function again in the if loop, the global variable tokens is not updated. It receives the new token constantly, but I cannot pass the updated token information to the def product_delete function.
import requests
import json
def producttoken():
url = "https://productapi.com/tokens"
payload = json.dumps({
"Username": "*",
"AppKey": "USER",
"Hash": "hzh8123sdgxzc123sdfdfhI1tOY="})
headers = {'Content-Type': 'application/json'}
response = requests.request("POST", url, headers=headers, data=payload)
strigns=response.text
stoken=str(strigns)
jtoken=json.loads(stoken)
token=jtoken['token']
print("token taken")
return token
tokens=producttoken()
counter = 0
def product_delete(product_id):
product_delete_url = "https://productapi.com/products/id/"+product_id;
headers = {
'authorization': "Token"+tokens,
'cache-control': "no-cache",}
response = requests.request("DELETE", product_delete_url, headers=headers)
r=response.text
if "expired_token" in r:
print("token renewed")
producttoken()
print(response.text)
for line in open('list.csv','r'):
line = line.rstrip('\n')
product_id = line.split(';')[0]
counter = counter + 1
product = product_delete(product_id)
print(counter)
producttoken()and the original linetokens=producttoken(). There's a key step you're missing in the "expired" renewal part.