app.py 1.9 KB

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