saver.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. import sys
  3. import logging
  4. class InvalidSaveConfigsError(Exception):
  5. def __init__(self, message, errors):
  6. # Call the base class constructor with the parameters it needs
  7. super(InvalidSaveConfigsError, self).__init__(message)
  8. class Saver(object):
  9. """
  10. get task from item queue, then save item to local storage
  11. """
  12. def __init__(self, save_configs=None):
  13. self._save_configs = save_configs
  14. if save_configs['type'] == 'file':
  15. write_path = self._save_configs['path']
  16. self._file_obj = open(write_path, 'w')
  17. elif save_configs['type'] == 'db':
  18. self._conn_pool = None
  19. return
  20. async def save(self, url, item):
  21. """
  22. try to save result according to save configs
  23. """
  24. try:
  25. configs = self._save_configs
  26. if configs['type'] == 'file':
  27. await self.save_to_file(url, item, self._file_obj)
  28. elif configs['type'] == 'db':
  29. await self.save_to_db()
  30. else:
  31. raise InvalidSaveConfigsError
  32. except InvalidSaveConfigsError:
  33. logging.error("invalid save configs, update 'save' field in the config.json")
  34. return
  35. async def save_to_file(self, url, item, file_obj):
  36. """
  37. save the item to a file, must "try, except" and don't change the parameters and return
  38. :return status:
  39. """
  40. logging.debug("%r start: url=%r", self.__class__.__name__, url)
  41. status = 0
  42. try:
  43. write_path = self._save_configs['path']
  44. item_str = ", ".join(str(x) for x in item)
  45. line = url + ": " + item_str + '\n'
  46. file_obj.write(line)
  47. # TODO: substitute to more specific exception
  48. except Exception as e:
  49. status = -1
  50. logging.error("%r error: %r, url=%r",
  51. self.__class__.__name__, e, url)
  52. logging.debug("%r end: status=%r, url=%r",
  53. self.__class__.__name__, status, url)
  54. return status
  55. async def save_to_db(self):
  56. """
  57. save the item to a database
  58. """
  59. raise NotImplementedError