config.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. # 16MB
  30. app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
  31. app.secret_key = config.secret_key
  32. return App(
  33. config=config,
  34. db=playhouse.sqlite_ext.SqliteExtDatabase(None),
  35. serializer=itsdangerous.URLSafeTimedSerializer(config.secret_key),
  36. app=app,
  37. )
  38. def init_db(self):
  39. self.db.init(self.config.db_path)
  40. def in_memory_db(self):
  41. try:
  42. self.db.close()
  43. except Exception:
  44. pass
  45. self.db.init(":memory:")
  46. def close_db(self):
  47. self.db.close()
  48. def serialize_token(self, obj: Any) -> str:
  49. return self.serializer.dumps(obj)
  50. def load_token(self, token: str) -> Any:
  51. return self.serializer.loads(token)
  52. app = App.from_env()
  53. if sys.stderr.isatty():
  54. def log(msg):
  55. sys.stderr.write(str(msg))
  56. sys.stderr.write("\n")
  57. else:
  58. def log(msg):
  59. sys.stderr.write("\x1b[31m")
  60. sys.stderr.write(str(msg))
  61. sys.stderr.write("\x1b[39m\n")