application_part.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import sqlmodel
  2. import sqlalchemy.engine.base
  3. from .validators import validator
  4. from .validators import validator_result
  5. class application_part:
  6. """
  7. This class is parent for parts of the applications. It define responses
  8. and method for access to database.
  9. """
  10. def __init__(self, database: sqlalchemy.engine.base.Engine) -> None:
  11. """
  12. This initialize part of application, database connection is required
  13. to have access to it in the application parts.
  14. Parameters:
  15. database (Engine): Database connection
  16. """
  17. self.__connector = database
  18. @property
  19. def _connector(self) -> sqlalchemy.engine.base.Engine:
  20. """ It return connection to database. """
  21. return self.__connector
  22. def _apikey_response(self, apikey: str) -> dict:
  23. """ It return response with apikey. """
  24. return self._success_response(apikey = apikey)
  25. def _validation(self, name: str, target: validator) -> dict | None:
  26. """
  27. This help validating. It require name of the validation, and
  28. validator. Then validate, and if validator is fine, return None
  29. or when something is bad, then return response.
  30. Parameters:
  31. name (str): Name of the validation
  32. target (validator): Validator to check
  33. Returns:
  34. (dict | None): Response with error or None on success
  35. """
  36. result = target.result
  37. if result == validator_result.valid:
  38. return None
  39. return self._fail_response(
  40. code = int(result),
  41. description = validator_result.name(result),
  42. validating = name
  43. )
  44. def _success_response(self, **kwargs) -> dict:
  45. """ It returns success response, with additional params. """
  46. base = dict()
  47. base.update(kwargs)
  48. base["status"] = "success"
  49. return base
  50. def _fail_no_apikey(self) -> dict:
  51. """ This return error response for not founded ApiKey. """
  52. return self._fail_response(cause = "ApiKey not exists.")
  53. def _fail_bad_password(self) -> dict:
  54. """ This return error response to use when bad password provided. """
  55. return self._fail_response(cause = "Password validation incorrect.")
  56. def _fail_response(self, **kwargs) -> dict:
  57. """ It return fail response, with additions content. """
  58. base = dict()
  59. base.update(kwargs)
  60. base["status"] = "fail"
  61. return base