app.py 2.5 KB

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