Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Render template blocks and send email
Krzysiek Szularz7886a3b18582
diff --git a/communication/__init__.py b/communication/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/communication/mail.py b/communication/mail.pynew file mode 100644index 0000000000..6426f4b5a2--- /dev/null+++ b/communication/mail.py@@ -0,0 +1,28 @@+from django.conf import settings+from django.core.mail.message import EmailMultiAlternatives+from django.template import Context+from django.template.loader import get_template+from django.template.loader_tags import BlockNode++BLOCKS = [SUBJECT, TEXT, HTML] = 'subject', 'text', 'html' # template blocks+++def send_email(address, template_name, context=None):+ """Renders template blocks and sends an email."""+ blocks = render_blocks(template_name=template_name, context=context or {})+ message = EmailMultiAlternatives(+ subject=blocks[SUBJECT],+ body=blocks[TEXT],+ from_email=settings.DEFAULT_FROM_EMAIL,+ to=[address])+ if HTML in blocks:+ message.attach_alternative(blocks[HTML], 'text/html')+ message.send()+++def render_blocks(template_name, context):+ """Renders BLOCKS from template. Block needs to be a top level node."""+ context = Context(context)+ template = get_template(template_name=template_name)+ return dict((node.name, node.render(context)) for node in template+ if isinstance(node, BlockNode) and node.name in BLOCKS)diff --git a/communication/tests.py b/communication/tests.pynew file mode 100644index 0000000000..5b5542b6a8--- /dev/null+++ b/communication/tests.py@@ -0,0 +1,70 @@+from communication.mail import SUBJECT, TEXT, HTML, send_email, render_blocks++from mock import Mock, patch, sentinel+from unittest2 import TestCase++from django.template.loader_tags import BlockNode+++class SendEmailTestCase(TestCase):++ def setUp(self):+ patcher = patch('communication.mail.settings')+ self.settings_mock = patcher.start()+ patcher = patch('communication.mail.render_blocks')+ self.render_mock = patcher.start()+ patcher = patch('communication.mail.EmailMultiAlternatives')+ self.email_mock = patcher.start()++ self.settings_mock.DEFAULT_FROM_EMAIL = sentinel.from_email++ def test_sending_email_without_html(self):+ """Html content is not attached when html block is missing"""+ self.render_mock.return_value = {SUBJECT: sentinel.subject,+ TEXT: sentinel.text}+ send_email(address=sentinel.address,+ template_name=sentinel.template_name,+ context=sentinel.context)+ self.assert_email_constructed()+ self.email_mock().send.assert_called_once()++ def test_sending_email_with_html(self):+ """Html content is attached when html block present"""+ self.render_mock.return_value = {SUBJECT: sentinel.subject,+ TEXT: sentinel.text,+ HTML: sentinel.html}+ send_email(address=sentinel.address,+ template_name=sentinel.template_name,+ context=sentinel.context)+ self.assert_email_constructed()+ self.email_mock().attach_alternative.assert_called_once_with(+ sentinel.html, 'text/html')+ self.email_mock().send.assert_called_once()++ def assert_email_constructed(self):+ self.email_mock.assert_called_once_with(+ subject=sentinel.subject,+ body=sentinel.text,+ from_email=sentinel.from_email,+ to=[sentinel.address])++ def tearDown(self):+ patch.stopall()+++class RenderBlocksTestCase(TestCase):++ @patch('communication.mail.get_template')+ @patch('communication.mail.Context')+ def test_block_rendering(self, context_mock, get_template_mock):+ """Template blocks are rendered with proper context"""+ html_block = Mock(spec=BlockNode)+ html_block.name = HTML+ some_block = Mock(spec=BlockNode)+ some_block.name = 'some_block'+ non_block = Mock()+ get_template_mock.return_value = [html_block, some_block, non_block]+ blocks = render_blocks(template_name=sentinel.template_name,+ context=sentinel.context)+ self.assertEquals(blocks, {HTML: html_block.render()})+ context_mock.assert_called_once_with(sentinel.context)diff --git a/registration/forms.py b/registration/forms.pyindex 745ecd28e1..d407bd864c 100644--- a/registration/forms.py+++ b/registration/forms.py@@ -1,15 +1,12 @@from django import formsfrom django.contrib.auth import authenticate, get_user_modelfrom django.contrib.auth.forms import AuthenticationForm, SetPasswordForm-from django.core.mail.message import EmailMessage-from django.core.urlresolvers import reverse-from django.template.loader import render_to_stringfrom django.utils.translation import ugettext_lazy as _from .models import EmailConfirmationRequest, ExternalUserDatafrom .utils import get_client_class_for_service-import urlparse+from communication.mail import send_emailUser = get_user_model()@@ -29,14 +26,10 @@ class RequestEmailConfirmationForm(forms.Form):def send(self):email = self.cleaned_data['email']- EmailConfirmationRequest.objects.filter(email=email).delete()request = EmailConfirmationRequest.objects.create(email=email)- path = reverse('registration:confirm_email',- kwargs={'token': request.token})- context = {'confirmation_url': urlparse.urljoin(self.local_host, path)}- msg = render_to_string('registration/email/confirm_email.txt', context)- subject = _('Email confirmation')- EmailMessage(subject, msg, to=[email]).send()+ confirmation_url = self.local_host + request.get_confirmation_url()+ context = {'confirmation_url': confirmation_url}+ send_email(email, 'registration/emails/confirm_email.txt', context)class EmailConfirmationForm(SetPasswordForm):diff --git a/registration/models.py b/registration/models.pyindex ee054cf51f..eb9ae9c8b6 100644--- a/registration/models.py+++ b/registration/models.py@@ -3,6 +3,7 @@ from datetime import timedeltafrom django.db import modelsfrom django.contrib.auth import get_user_modelfrom django.conf import settings+from django.core.urlresolvers import reversefrom django.utils import timezonefrom django.utils.crypto import get_random_string@@ -53,3 +54,7 @@ class EmailConfirmationRequest(models.Model):def get_or_create_user(self):user, _created = User.objects.get_or_create(email=self.email)return user++ def get_confirmation_url(self):+ return reverse('registration:confirm_email',+ kwargs={'token': self.token})diff --git a/registration/templates/registration/email/confirm_email.txt b/registration/templates/registration/emails/confirm_email.txtsimilarity index 55%rename from registration/templates/registration/email/confirm_email.txtrename to registration/templates/registration/emails/confirm_email.txtindex bf467e4089..f3c175fcd2 100644--- a/registration/templates/registration/email/confirm_email.txt+++ b/registration/templates/registration/emails/confirm_email.txt@@ -1,4 +1,8 @@-Hi!+{% load i18n %}++{% block subject %}{% trans "Confirm your email address" %}{% endblock %}++{% block text %}{% blocktrans %}Hi!You have requested login access to saleor project. To continue visit the link below.@@ -7,4 +11,4 @@ You have requested login access to saleor project. To continue visit the link beIf you didn't try to login to saleor please ignore this message. We apologise for inconvenience.Sincerely,-Saleor Team+Saleor Team{% endblocktrans %}{% endblock %}