base.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. import os.path
  2. import sys
  3. from flask import Flask, url_for, request, current_app
  4. from flask_mail import Mail
  5. from flask_login import LoginManager, current_user
  6. from flask.logging import default_handler
  7. from typing import Optional
  8. import logging.handlers
  9. import logging
  10. from configure import conf
  11. from core.user import AnonymousUser
  12. class App:
  13. def __init__(self, import_name: str):
  14. self._app = Flask(import_name)
  15. self._app.config["SECRET_KEY"] = conf['secret-key']
  16. self.login_manager = LoginManager()
  17. self.login_manager.init_app(self._app)
  18. self.login_manager.anonymous_user = AnonymousUser # 设置未登录的匿名对象
  19. self._app.config["MAIL_SERVER"] = conf['email_server']
  20. self._app.config["MAIL_PORT"] = conf['email_port']
  21. self._app.config["MAIL_USE_TLS"] = conf['email_tls']
  22. self._app.config["MAIL_USE_SSL"] = conf['email_ssl']
  23. self._app.config["MAIL_USERNAME"] = conf['email_name']
  24. self._app.config["MAIL_PASSWORD"] = conf['email_passwd']
  25. self.mail = Mail(self._app)
  26. self._app.logger.removeHandler(default_handler)
  27. self._app.logger.setLevel(conf["log-level"])
  28. self._app.logger.propagate = False
  29. if conf["log-home"] is not None:
  30. handle = logging.handlers.TimedRotatingFileHandler(
  31. os.path.join(conf["log-home"], f"flask-{os.getpid()}.log"))
  32. handle.setFormatter(logging.Formatter(conf["log-format"]))
  33. self._app.logger.addHandler(handle)
  34. if conf["log-stderr"]:
  35. handle = logging.StreamHandler(sys.stderr)
  36. handle.setFormatter(logging.Formatter(conf["log-format"]))
  37. self._app.logger.addHandler(handle)
  38. def get_app(self) -> Flask:
  39. return self._app
  40. def run(self):
  41. self.run()
  42. @staticmethod
  43. def get_max_page(count: int, count_page: int):
  44. return (count // count_page) + (0 if count % count_page == 0 else 1)
  45. @staticmethod
  46. def get_page(url, page: int, count: int):
  47. if count <= 9:
  48. page_list = [[f"{i + 1}", url_for(url, page=i + 1)] for i in range(count)]
  49. elif page <= 5:
  50. """
  51. [1][2][3][4][5][6][...][count - 1][count]
  52. """
  53. page_list = [[f"{i + 1}", url_for(url, page=i + 1)] for i in range(6)]
  54. page_list += [None,
  55. [f"{count - 1}", url_for(url, page=count - 1)],
  56. [f"{count}", url_for(url, page=count)]]
  57. elif page >= count - 5:
  58. """
  59. [1][2][...][count - 5][count - 4][count - 3][count - 2][count - 1][count]
  60. """
  61. page_list: Optional[list] = [["1", url_for(url, page=1)],
  62. ["2", url_for(url, page=2)],
  63. None]
  64. page_list += [[f"{count - 5 + i}", url_for(url, page=count - 5 + i), False] for i in range(6)]
  65. else:
  66. """
  67. [1][2][...][page - 2][page - 1][page][page + 1][page + 2][...][count - 1][count]
  68. """
  69. page_list: Optional[list] = [["1", url_for(url, page=1)],
  70. ["2", url_for(url, page=2)],
  71. None]
  72. page_list += [[f"{page - 2 + i}", url_for(url, page=page - 2 + i)] for i in range(5)]
  73. page_list += [None,
  74. [f"{count - 1}", url_for(url, page=count - 1)],
  75. [f"{count}", url_for(url, page=count)]]
  76. return page_list
  77. @staticmethod
  78. def __get_log_request_info():
  79. return (f"user: '{current_user.email}' "
  80. f"url: '{request.url}' blueprint: '{request.blueprint}' "
  81. f"args: {request.args} form: {request.form} "
  82. f"accept_encodings: '{request.accept_encodings}' "
  83. f"accept_charsets: '{request.accept_charsets}' "
  84. f"accept_mimetypes: '{request.accept_mimetypes}' "
  85. f"accept_languages: '{request.accept_languages}'")
  86. @staticmethod
  87. def print_load_page_log(page: str):
  88. current_app.logger.debug(
  89. f"[{request.method}] Load - '{page}' " + App.__get_log_request_info())
  90. @staticmethod
  91. def print_form_error_log(opt: str):
  92. current_app.logger.warning(
  93. f"[{request.method}] '{opt}' - Bad form " + App.__get_log_request_info())
  94. @staticmethod
  95. def print_sys_opt_fail_log(opt: str):
  96. current_app.logger.error(
  97. f"[{request.method}] System {opt} - fail " + App.__get_log_request_info())
  98. @staticmethod
  99. def print_sys_opt_success_log(opt: str):
  100. current_app.logger.warning(
  101. f"[{request.method}] System {opt} - success " + App.__get_log_request_info())
  102. @staticmethod
  103. def print_user_opt_fail_log(opt: str):
  104. current_app.logger.debug(
  105. f"[{request.method}] User {opt} - fail " + App.__get_log_request_info())
  106. @staticmethod
  107. def print_user_opt_success_log(opt: str):
  108. current_app.logger.debug(
  109. f"[{request.method}] User {opt} - success " + App.__get_log_request_info())
  110. @staticmethod
  111. def print_user_opt_error_log(opt: str):
  112. current_app.logger.warning(
  113. f"[{request.method}] User {opt} - system fail " + App.__get_log_request_info())
  114. @staticmethod
  115. def print_import_user_opt_success_log(opt: str):
  116. current_app.logger.info(
  117. f"[{request.method}] User {opt} - success " + App.__get_log_request_info())
  118. @staticmethod
  119. def print_user_not_allow_opt_log(opt: str):
  120. current_app.logger.info(
  121. f"[{request.method}] User '{opt}' - reject " + App.__get_log_request_info())