from__future__importannotationsimportenumimporttypingfromimportlibimportimport_modulefrompyflocker.ciphersimportexc_DEFAULT_BACKEND=Noneiftyping.TYPE_CHECKING:# pragma: no coverimporttypesfromtypesimportModuleType
[docs]classBackends(enum.Enum):"""The backends of PyFLocker."""CRYPTOGRAPHY="cryptography"CRYPTODOME="cryptodome"
[docs]defload_algorithm(name:str,backend:Backends|None=None)->types.ModuleType:"""Load a specific algorithm from the given ``backend``. Args: name: The name of the algorithm. backend: The backend to use. Returns: module: Algorithm module from the required backend. Raises: UnsupportedAlgorithm: This is raised if the algorithm is not found in the backend. """_backend=load_backend(backend)try:returnimport_module(f".{name}",_backend.__name__)exceptImportErrorase:msg=f"{name} is not implemented by backend {backend}."raiseexc.UnsupportedAlgorithm(msg)frome
[docs]defload_backend(backend:Backends|None=None,)->types.ModuleType:"""Load a backend. Args: backend: An attribute from :class:`Backends` class. Returns: module: The backend module. """# Rules:# 1. if default is present and backend is None: return default# 2. if backend is given:# 2.1. don't set default# 2.2. load that particular backend or raise# otherwise find a backend or raise# once the backend is found, set it as defaultglobal_DEFAULT_BACKENDifbackendisNone:if_DEFAULT_BACKENDisNone:_DEFAULT_BACKEND=_find_backend()return_DEFAULT_BACKEND# type: ignore# backend is not Noneifnotisinstance(backend,Backends):msg="argument backend must be of type Backends."raiseTypeError(msg)if_DEFAULT_BACKENDisNone:_DEFAULT_BACKEND=_import_helper(backend)return_DEFAULT_BACKEND# noqa: PIE781return_import_helper(backend)