apikey.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. class bad_apikey_exception(Exception):
  3. """ This error would be raised, when bad apikey occur. """
  4. def __init__(self) -> None:
  5. super("Provided ApiKey not exists in database.")
  6. class apikey:
  7. """
  8. This create new random API key.
  9. """
  10. def __new__(cls, lenght: int = 128) -> str:
  11. """
  12. This create new random API key.
  13. lenght: int - Lenght os the api key (default: 128)
  14. return: str - API key
  15. """
  16. byte = cls.__get_random(lenght)
  17. string = cls.__to_hex(byte)
  18. return string
  19. def __to_hex(byte: bytes) -> str:
  20. """
  21. This convert random bytes to string.
  22. byte: bytes - Bytes array to convert
  23. return: str - Result as string
  24. """
  25. return byte.hex()
  26. def __get_random(lenght: int) -> bytes:
  27. """
  28. Get random count of hex chars from os.
  29. lenght: int - Lenght of the bytes
  30. return: bytes - Random bytes from os
  31. """
  32. return os.urandom(lenght)