DeaD_EyE

config token json example with appdirs and Path

Sep 30th, 2020
51
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import json
  2. import sys
  3. from getpass import getpass
  4. from pathlib import Path
  5.  
  6. from appdirs import user_config_dir
  7. https://pypi.org/project/appdirs/
  8.  
  9. config_dir = Path(user_config_dir(), "programm")
  10. token_file = config_dir / "token.conf"
  11.  
  12. print("token_file:", token_file)
  13. print("token_file.parent:", token_file.parent)
  14. print("config_dir:", config_dir)
  15.  
  16. config_dir.mkdir(exist_ok=True)
  17.  
  18.  
  19. def get_creds():
  20.     token = input("Token: ")
  21.     username = input("Username: ")
  22.     password = getpass()
  23.     # maybe not required to hide password
  24.     return {"token": token, "username": username, "password": password}
  25.  
  26.  
  27. def load_token():
  28.     if token_file.exists():
  29.         with token_file.open() as fd:
  30.             try:
  31.                 credentials = json.load(fd)
  32.             except ValueError:
  33.                 # print(f"Invalid json data in token file: {token_file}", file=sys.stderr)
  34.                 raise SystemExit(f"Invalid json data in token file: {token_file}")
  35.     else:
  36.         credentials = get_creds()
  37.         with token_file.open("w") as fd:
  38.             json.dump(credentials, fd)
  39.     return credentials
  40.  
  41.  
  42. if __name__ == "__main__":
  43.     print(load_token())
RAW Paste Data