app.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import traceback
  2. from flask import Flask, request
  3. from api import *
  4. from api import login, search
  5. logs_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')
  6. os.makedirs(logs_folder, exist_ok=True)
  7. current_folder = os.path.dirname(os.path.abspath(__file__))
  8. file_handler = logging.FileHandler(filename=f"{current_folder}/logs/app.log", encoding="utf-8")
  9. # 配置日志格式
  10. formatter = logging.Formatter("%(asctime)s %(levelname)s[%(funcName)s:%(lineno)s]:%(message)s", "%Y-%m-%d %H:%M:%S")
  11. file_handler.setFormatter(formatter)
  12. console_handler = logging.StreamHandler()
  13. # 配置日志记录器
  14. logger = logging.getLogger()
  15. logger.setLevel(logging.INFO)
  16. logger.addHandler(file_handler)
  17. # 开发的时候打开这行注释,日志会打印在控制台上面
  18. logger.addHandler(console_handler)
  19. app = Flask(__name__)
  20. app.register_blueprint(login.login_opt, url_prefix="/login")
  21. app.register_blueprint(search.search_opt, url_prefix="/search")
  22. @app.errorhandler(Exception)
  23. def handle_exception(error: Exception):
  24. """
  25. 全局异常处理
  26. """
  27. status_code = 500
  28. if isinstance(error, BusinessException):
  29. status_code = 200
  30. response = fail_response(error.msg)
  31. else:
  32. logging.error(error)
  33. traceback.print_exc()
  34. response = fail_response(str(error))
  35. return response, status_code
  36. @app.before_request
  37. def log_request():
  38. """
  39. 打印请求
  40. """
  41. logging.info('Request: %s %s', request.method, request.url)
  42. logging.info('Request Body: %s', request.get_data(as_text=True))
  43. @app.after_request
  44. def log_response(response):
  45. """
  46. 打印返回
  47. """
  48. data = response.get_data(as_text=True)
  49. if len(data) > 1000:
  50. logging.info('Response Body: %s', data[:1000] + "...")
  51. else:
  52. logging.info('Response Body: %s', data)
  53. return response
  54. if __name__ == '__main__':
  55. app.run(host="0.0.0.0", port=8990, threaded=True)