store.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import os
  2. import pandas as pd
  3. from log import PPLogger
  4. from setting import CSV_FILENAME, CSV_DIR
  5. from threading import Lock
  6. pd.options.display.max_colwidth = 100000
  7. class WuBaStore:
  8. def __init__(self, method):
  9. """
  10. 持久化
  11. :param method: 持久化方式 :'csv',,,
  12. """
  13. self.method = method
  14. self.logger = PPLogger(name='store')
  15. self.logger.setup_logger()
  16. self.lock = Lock()
  17. def run(self, *args):
  18. if self.method == 'csv':
  19. self.to_csv(args[0])
  20. else:
  21. pass
  22. def to_csv(self, data_dict: dict, file_dir: str = CSV_DIR, file_name: str = CSV_FILENAME):
  23. if not os.path.exists(file_dir):
  24. os.mkdir(file_dir)
  25. try:
  26. file_path = os.path.join(file_dir, file_name)
  27. data = pd.DataFrame([data_dict])
  28. with self.lock:
  29. if not os.path.exists(file_path):
  30. data.to_csv(path_or_buf=file_path, index=False, header=True, encoding='utf8')
  31. else:
  32. data.to_csv(path_or_buf=file_path, index=False, header=False, encoding='utf8', mode='a')
  33. except Exception as e:
  34. self.logger.error(e)