load_data.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import logging
  4. import sys
  5. import os
  6. from datetime import datetime
  7. # 配置日志记录器
  8. logging.basicConfig(
  9. level=logging.INFO,
  10. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  11. handlers=[
  12. logging.StreamHandler(sys.stdout)
  13. ]
  14. )
  15. logger = logging.getLogger("load_data")
  16. def load_data_from_source(source_name="default", execution_date=None, execution_mode=None, script_name=None):
  17. """从数据源加载数据的示例函数"""
  18. if execution_date is None:
  19. execution_date = datetime.now()
  20. # 获取当前脚本的文件名(如果没有传入)
  21. if script_name is None:
  22. script_name = os.path.basename(__file__)
  23. # 使用print输出所有参数
  24. print(f"===== 参数信息 (print输出) =====")
  25. print(f"table_name: {source_name}")
  26. print(f"exec_date: {execution_date}")
  27. print(f"execution_mode: {execution_mode}")
  28. print(f"script_name: {script_name}")
  29. print(f"================================")
  30. # 使用logger.info输出所有参数
  31. logger.info(f"===== 参数信息 (logger输出) =====")
  32. logger.info(f"table_name: {source_name}")
  33. logger.info(f"exec_date: {execution_date}")
  34. logger.info(f"execution_mode: {execution_mode}")
  35. logger.info(f"script_name: {script_name}")
  36. logger.info(f"================================")
  37. return True
  38. def run(table_name, execution_mode, exec_date=None, script_name=None, **kwargs):
  39. """
  40. 统一入口函数,符合Airflow动态脚本调用规范
  41. 参数:
  42. table_name (str): 要处理的表名
  43. execution_mode (str): 执行模式 (append/full_refresh)
  44. exec_date: 执行日期
  45. script_name: 脚本名称
  46. **kwargs: 其他可能的参数
  47. 返回:
  48. bool: 执行成功返回True,否则返回False
  49. """
  50. logger.info(f"开始执行脚本...")
  51. # 打印所有传入的参数
  52. logger.info(f"===== 传入参数信息 =====")
  53. logger.info(f"table_name: {table_name}")
  54. logger.info(f"execution_mode: {execution_mode}")
  55. logger.info(f"exec_date: {exec_date}")
  56. logger.info(f"script_name: {script_name}")
  57. # 打印所有可能的额外参数
  58. for key, value in kwargs.items():
  59. logger.info(f"额外参数 - {key}: {value}")
  60. logger.info(f"========================")
  61. # 实际调用内部处理函数
  62. return load_data_from_source(
  63. source_name=table_name,
  64. execution_date=exec_date,
  65. execution_mode=execution_mode,
  66. script_name=script_name
  67. )
  68. if __name__ == "__main__":
  69. # 直接执行时调用统一入口函数,传入测试参数
  70. run(
  71. table_name="test_table",
  72. execution_mode="append",
  73. exec_date=datetime.now(),
  74. script_name=os.path.basename(__file__)
  75. )