app.py 2.2 KB

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