Refactor: split code into several django apps (we call them modules).
This commit is contained in:
59
dav_base/emails.py
Normal file
59
dav_base/emails.py
Normal file
@@ -0,0 +1,59 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
from django.apps import apps
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.mail import EmailMessage
|
||||
from django.template.loader import get_template
|
||||
|
||||
app_config = apps.get_containing_app_config(__package__)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AbstractMail(object):
|
||||
_subject = u''
|
||||
_template_name = None
|
||||
|
||||
def _get_sender(self):
|
||||
#app_config = apps.get_containing_app_config(__package__)
|
||||
return app_config.settings.email_sender
|
||||
|
||||
def _get_subject(self, subject_fmt=None, **kwargs):
|
||||
if subject_fmt is None:
|
||||
subject_fmt = self._subject
|
||||
#app_config = apps.get_containing_app_config(__package__)
|
||||
if app_config.settings.email_subject_prefix:
|
||||
subject_fmt = u'%s %s' % (app_config.settings.email_subject_prefix, subject_fmt)
|
||||
subject = subject_fmt.format(**kwargs)
|
||||
return subject
|
||||
|
||||
def _get_template(self):
|
||||
if not self._template_name:
|
||||
raise ImproperlyConfigured('%s._template_name ist not set.', self.__class__.__name__)
|
||||
return get_template(self._template_name, using='PLAINTEXT')
|
||||
|
||||
def _get_context_data(self, extra_context=None):
|
||||
#app_config = apps.get_containing_app_config(__package__)
|
||||
context = {
|
||||
'base_url': app_config.settings.email_base_url,
|
||||
}
|
||||
if extra_context:
|
||||
context.update(extra_context)
|
||||
return context
|
||||
|
||||
def _get_body(self, context=None):
|
||||
template = self._get_template()
|
||||
context = self._get_context_data(extra_context=context)
|
||||
return template.render(context)
|
||||
|
||||
def _get_recipients(self):
|
||||
raise NotImplementedError()
|
||||
|
||||
def send(self):
|
||||
subject = self._get_subject()
|
||||
body = self._get_body()
|
||||
sender = self._get_sender()
|
||||
recipients = self._get_recipients()
|
||||
|
||||
email = EmailMessage(subject=subject, body=body, from_email=sender, to=recipients)
|
||||
logger.info(u'Send %s to %s', self.__class__.__name__, recipients)
|
||||
email.send()
|
||||
Reference in New Issue
Block a user