If you want to hide your username in the script as well you can use credentials of the keyring module. Also I would recommend to use the getpass library for the input of the password; this prevents the password to be printed to screen. Finally, you may want to have a delete credentials somewhere in your code as soon as you notice that the login failed. Otherwise the script restart without the prompt to the user. As a full example. Here is how you would retrieve the username and password
import getpass
import keyring
import requests
service_name = "Name of the keyring"
credentials = keyring.get_credential(service_name, None)
if credentials is None:
username = input("Username: ")
password = getpass.getpass()
keyring.set_password(service_name,username, password)
else:
username = credentials.username
password = credentials.password
Then you can do your thing, for instance do a post using request to an api. If it fails, delete the keyring to force to ask the credenitials again.
response = requests.post('url_to_api', auth=requests.auth.HTTPBasicAuth(username, password))
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
keyring.delete_password(service_name, username)
raise
If the login succeeds, the next time you don't have to input username and password again.
c.username
andc.password
. – Beamon