I want to use a .txt file to store API tokens for an application, but I got stuck trying to find a way to Replace the API key/token if it's found in the file. This is the code tried (Python 3.5):
data_to_save = {}
data_to_save['savetime'] = str(datetime.datetime.now())[:19]
data_to_save['api_key'] = key_submitted
data_to_save['user'] = uniqueid
api_exists = False
user_exists = False
with open("databases/api_keys.txt", 'r+') as f:
database = json.loads(f.read())
for i in database:
if i['api_key'] == key_submitted:
send_text_to_user(userid, "[b]Error: That API key is already in use.[/b]", "red")
api_exists = True
if i['user'] == uniqueid:
user_exists = True
if user_exists == True:
if api_exists = True:
send_text_to_user(userid, "[b]Error: Your API key was already saved at another time.[/b]", "red")
else:
f.write(json.dumps(data_to_save)) #Here, StackOverflow
send_text_to_user(userid, "[b]Okay, I replaced your API key.[/b]", "green")
f.close()
if user_exists == False:
writing = open("databases/api_keys.txt", 'a')
writing.write(json.dumps(data_to_save))
writing.close()
I also want to know if this is the best way to do it or the code could be optimized and how.
Thank you, it has been done. Final code:
data_to_save = {'savetime': str(datetime.datetime.now())[:19], 'api_key': key_submitted, 'user': uniqueid}
with open("databases/api_keys.txt", 'r') as f:
database = json.loads(f.read())
for i in database:
if i['user'] == uniqueid:
database.remove(i)
if i['api_key'] == key_submitted:
send_text_to_user(userid, "[b]Error: That API key is already in use.[/b]", "red")
api_exists = True
break
if not api_exists:
database.append(data_to_save)
f.write(json.dumps(database)
send_text_to_user(userid, "[b]Okay, your API key was succesfully stored.[/b]")
With this approach we don't even need to write different saves just in case the user exists or doesn't exists because it deletes it if it's found, so it never exists when the code runs and it just need to save a "new" record every single time, except if the API key already belongs to another user.