/pgcontents/managerbase.py

https://github.com/quantopian/pgcontents · Python · 101 lines · 75 code · 20 blank · 6 comment · 2 complexity · 3d28fe629c0409c2889eb5e207a567b6 MD5 · raw file

  1. """
  2. Mixin for classes interacting with the pgcontents database.
  3. """
  4. from getpass import getuser
  5. from sqlalchemy import (
  6. create_engine,
  7. )
  8. from sqlalchemy.engine.base import Engine
  9. from tornado.web import HTTPError
  10. from .constants import UNLIMITED
  11. from .crypto import NoEncryption
  12. from .query import ensure_db_user
  13. from .utils.ipycompat import Any, Bool, Instance, Integer, HasTraits, Unicode
  14. class PostgresManagerMixin(HasTraits):
  15. """
  16. Shared behavior for Postgres-backed ContentsManagers.
  17. """
  18. db_url = Unicode(
  19. default_value="postgresql://{user}@/pgcontents".format(
  20. user=getuser(),
  21. ),
  22. config=True,
  23. help="Connection string for the database.",
  24. )
  25. user_id = Unicode(
  26. default_value=getuser(),
  27. allow_none=True,
  28. config=True,
  29. help="Name for the user whose contents we're managing.",
  30. )
  31. create_user_on_startup = Bool(
  32. default_value=True,
  33. config=True,
  34. help="Create a user for user_id automatically?",
  35. )
  36. max_file_size_bytes = Integer(
  37. default_value=UNLIMITED,
  38. config=True,
  39. help="Maximum size in bytes of a file that will be saved.",
  40. )
  41. crypto = Any(
  42. default_value=NoEncryption(),
  43. allow_none=False,
  44. config=True,
  45. help=(
  46. "Object with encrypt() and decrypt() methods to "
  47. "call on data entering/exiting the database.",
  48. )
  49. )
  50. engine = Instance(Engine)
  51. def _engine_default(self):
  52. return create_engine(self.db_url, echo=False)
  53. def __init__(self, *args, **kwargs):
  54. super(PostgresManagerMixin, self).__init__(*args, **kwargs)
  55. if self.create_user_on_startup:
  56. self.ensure_user()
  57. def ensure_user(self):
  58. with self.engine.begin() as db:
  59. ensure_db_user(db, self.user_id)
  60. def no_such_entity(self, path):
  61. self.do_404(
  62. u"No such entity: [{path}]".format(path=path)
  63. )
  64. def not_empty(self, path):
  65. self.do_400(
  66. u"Directory not empty: [{path}]".format(path=path)
  67. )
  68. def file_too_large(self, path):
  69. self.do_413(u"File is too large to save: [{path}]".format(path=path))
  70. def already_exists(self, path):
  71. self.do_409(u"File already exists: [{path}]".format(path=path))
  72. def do_400(self, msg):
  73. raise HTTPError(400, msg)
  74. def do_404(self, msg):
  75. raise HTTPError(404, msg)
  76. def do_409(self, msg):
  77. raise HTTPError(409, msg)
  78. def do_413(self, msg):
  79. raise HTTPError(413, msg)
  80. def do_500(self, msg):
  81. raise HTTPError(500, msg)