Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

filebased.py 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Email backend that writes messages to a file."""
  2. import datetime
  3. import os
  4. from django.conf import settings
  5. from django.core.exceptions import ImproperlyConfigured
  6. from django.core.mail.backends.console import (
  7. EmailBackend as ConsoleEmailBackend,
  8. )
  9. class EmailBackend(ConsoleEmailBackend):
  10. def __init__(self, *args, file_path=None, **kwargs):
  11. self._fname = None
  12. if file_path is not None:
  13. self.file_path = file_path
  14. else:
  15. self.file_path = getattr(settings, 'EMAIL_FILE_PATH', None)
  16. # Make sure self.file_path is a string.
  17. if not isinstance(self.file_path, str):
  18. raise ImproperlyConfigured('Path for saving emails is invalid: %r' % self.file_path)
  19. self.file_path = os.path.abspath(self.file_path)
  20. # Make sure that self.file_path is a directory if it exists.
  21. if os.path.exists(self.file_path) and not os.path.isdir(self.file_path):
  22. raise ImproperlyConfigured(
  23. 'Path for saving email messages exists, but is not a directory: %s' % self.file_path
  24. )
  25. # Try to create it, if it not exists.
  26. elif not os.path.exists(self.file_path):
  27. try:
  28. os.makedirs(self.file_path)
  29. except OSError as err:
  30. raise ImproperlyConfigured(
  31. 'Could not create directory for saving email messages: %s (%s)' % (self.file_path, err)
  32. )
  33. # Make sure that self.file_path is writable.
  34. if not os.access(self.file_path, os.W_OK):
  35. raise ImproperlyConfigured('Could not write to directory: %s' % self.file_path)
  36. # Finally, call super().
  37. # Since we're using the console-based backend as a base,
  38. # force the stream to be None, so we don't default to stdout
  39. kwargs['stream'] = None
  40. super().__init__(*args, **kwargs)
  41. def write_message(self, message):
  42. self.stream.write(message.message().as_bytes() + b'\n')
  43. self.stream.write(b'-' * 79)
  44. self.stream.write(b'\n')
  45. def _get_filename(self):
  46. """Return a unique file name."""
  47. if self._fname is None:
  48. timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
  49. fname = "%s-%s.log" % (timestamp, abs(id(self)))
  50. self._fname = os.path.join(self.file_path, fname)
  51. return self._fname
  52. def open(self):
  53. if self.stream is None:
  54. self.stream = open(self._get_filename(), 'ab')
  55. return True
  56. return False
  57. def close(self):
  58. try:
  59. if self.stream is not None:
  60. self.stream.close()
  61. finally:
  62. self.stream = None