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)
CodePudding user response:
There are a lot of ways to update token
, such as using the class
base of your functions and using setter and getter. However, sending token
in argument to product_delete might be easier for you:
product = product_delete(product_id, token)
I hope it could help you ;)
CodePudding user response:
You can pass tokens
as second parameter in product_delete
function then using recursion to get new token and calling the function again with same product_id
.
tokens = producttoken()
counter = 0
def product_delete(product_id, tokens):
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")
product_delete(product_id, 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, tokens)
print(counter)