app.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import os
  2. from flask import Flask, request
  3. from MoneyRecord import MoneyRecord
  4. from user import User
  5. import logging
  6. from logging.handlers import TimedRotatingFileHandler
  7. from datetime import datetime
  8. app = Flask(__name__)
  9. @app.route('/')
  10. def hello_world(): # put application's code here
  11. return 'it works!'
  12. @app.route('/user/<action>', methods=['POST'])
  13. def user_action(action):
  14. data = request.get_json()
  15. r = User(action=action, data=data, logger=logger).user_router()
  16. return r
  17. @app.route('/money/<action>', methods=['POST'])
  18. def money_action(action):
  19. data = request.get_json()
  20. r = MoneyRecord(action=action, data=data, logger=logger).money_record_router()
  21. return r
  22. class CustomLogger:
  23. def __init__(self, log_file):
  24. self.log_file = log_file
  25. self.logger = self._create_logger()
  26. def _create_logger(self):
  27. logger = logging.getLogger(__name__)
  28. logger.setLevel(logging.INFO)
  29. # 创建 TimedRotatingFileHandler 对象
  30. handler = TimedRotatingFileHandler(self.log_file, when='midnight', backupCount=7)
  31. handler.setLevel(logging.INFO)
  32. # 设置日志格式
  33. formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d')
  34. handler.setFormatter(formatter)
  35. logger.addHandler(handler)
  36. return logger
  37. def log(self, message):
  38. self.logger.info(message)
  39. # 使用自定义的 logging 工具类
  40. # 获取当前日期
  41. current_date = datetime.now()
  42. # 获取年月日
  43. year = current_date.year
  44. month = current_date.month
  45. day = current_date.day
  46. # 将年月日格式化为字符串
  47. formatted_date = current_date.strftime("%Y-%m-%d")
  48. # logger = CustomLogger(f'{os.path.dirname(__file__)}/logs/{formatted_date}.log')
  49. # logger = CustomLogger(f'/Users/jasonphd/Desktop/gogs/JasonPhdWork/server/flaskProject/logs{formatted_date}.log')
  50. logger = CustomLogger(f'/Users/jasonphd/Desktop/gogs/JasonPhdWork/app/logs{formatted_date}.log')
  51. # 自定义中间件
  52. @app.before_request
  53. def log_request_info():
  54. logger.log(f"url:{request.url} params:{request.get_json()} method:{request.method} ip:{request.remote_addr}")
  55. if __name__ == '__main__':
  56. app.run(host='0.0.0.0',port=5005)