config.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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__, static_folder=os.path.join(os.getcwd(), config.static_path),
  27. )
  28. app.secret_key = config.secret_key
  29. return App(
  30. config=config,
  31. db=playhouse.sqlite_ext.SqliteExtDatabase(None),
  32. serializer=itsdangerous.URLSafeTimedSerializer(config.secret_key),
  33. app=app,
  34. )
  35. def init_db(self):
  36. self.db.init(self.config.db_path)
  37. def in_memory_db(self):
  38. try:
  39. self.db.close()
  40. except:
  41. pass
  42. self.db.init(":memory:")
  43. def close_db(self):
  44. self.db.close()
  45. def serialize_token(self, obj: Any) -> str:
  46. return self.serializer.dumps(obj)
  47. def load_token(self, token: str) -> Any:
  48. return self.serializer.loads(token)
  49. app = App.from_env()
  50. if sys.stderr.isatty():
  51. def log(msg):
  52. sys.stderr.write(str(msg))
  53. sys.stderr.write("\n")
  54. else:
  55. def log(msg):
  56. sys.stderr.write("\x1b[31m")
  57. sys.stderr.write(str(msg))
  58. sys.stderr.write("\x1b[39m\n")