config.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from dataclasses import dataclass
  2. import os
  3. import sys
  4. from typing import Any
  5. import environ
  6. import flask
  7. import itsdangerous
  8. import playhouse.sqlite_ext
  9. @environ.config(prefix="LC")
  10. class Config:
  11. secret_key = environ.var()
  12. app_path = environ.var()
  13. db_path = environ.var()
  14. static_path = environ.var("static")
  15. @dataclass
  16. class App:
  17. config: Config
  18. app: flask.Flask
  19. db: playhouse.sqlite_ext.SqliteExtDatabase
  20. serializer: itsdangerous.URLSafeTimedSerializer
  21. per_page: int = 50
  22. @staticmethod
  23. def from_env() -> "App":
  24. config = environ.to_config(Config)
  25. app = flask.Flask(
  26. __name__,
  27. static_folder=os.path.join(os.getcwd(), config.static_path),
  28. )
  29. app.secret_key = config.secret_key
  30. return App(
  31. config=config,
  32. db=playhouse.sqlite_ext.SqliteExtDatabase(None),
  33. serializer=itsdangerous.URLSafeTimedSerializer(config.secret_key),
  34. app=app,
  35. )
  36. def init_db(self):
  37. self.db.init(self.config.db_path)
  38. def in_memory_db(self):
  39. try:
  40. self.db.close()
  41. except Exception:
  42. pass
  43. self.db.init(":memory:")
  44. def close_db(self):
  45. self.db.close()
  46. def serialize_token(self, obj: Any) -> str:
  47. return self.serializer.dumps(obj)
  48. def load_token(self, token: str) -> Any:
  49. return self.serializer.loads(token)
  50. app = App.from_env()
  51. if sys.stderr.isatty():
  52. def log(msg):
  53. sys.stderr.write(str(msg))
  54. sys.stderr.write("\n")
  55. else:
  56. def log(msg):
  57. sys.stderr.write("\x1b[31m")
  58. sys.stderr.write(str(msg))
  59. sys.stderr.write("\x1b[39m\n")