Skip to content

Commit df881fd

Browse files
committed
Allow kwargs overrides for (nearly) all settings
* Update utils.get_anymail_setting to support kwargs override of django.conf.settings values * Use the updated version everywhere * Switch from ImproperlyConfigured to AnymailConfigurationError exception (anticipates feature_wehooks change) Closes #12
1 parent 6b415ee commit df881fd

File tree

10 files changed

+124
-38
lines changed

10 files changed

+124
-38
lines changed

anymail/backends/base.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,15 @@ class AnymailBaseBackend(BaseEmailBackend):
1717
def __init__(self, *args, **kwargs):
1818
super(AnymailBaseBackend, self).__init__(*args, **kwargs)
1919

20-
self.ignore_unsupported_features = get_anymail_setting("IGNORE_UNSUPPORTED_FEATURES", False)
21-
self.ignore_recipient_status = get_anymail_setting("IGNORE_RECIPIENT_STATUS", False)
20+
self.ignore_unsupported_features = get_anymail_setting('ignore_unsupported_features',
21+
kwargs=kwargs, default=False)
22+
self.ignore_recipient_status = get_anymail_setting('ignore_recipient_status',
23+
kwargs=kwargs, default=False)
2224

2325
# Merge SEND_DEFAULTS and <esp_name>_SEND_DEFAULTS settings
24-
send_defaults = get_anymail_setting("SEND_DEFAULTS", {})
25-
esp_send_defaults = get_anymail_setting("%s_SEND_DEFAULTS" % self.esp_name.upper(), None)
26+
send_defaults = get_anymail_setting('send_defaults', default={}) # but not from kwargs
27+
esp_send_defaults = get_anymail_setting('send_defaults', esp_name=self.esp_name,
28+
kwargs=kwargs, default=None)
2629
if esp_send_defaults is not None:
2730
send_defaults = send_defaults.copy()
2831
send_defaults.update(esp_send_defaults)

anymail/backends/mailgun.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ class MailgunBackend(AnymailRequestsBackend):
1414

1515
def __init__(self, **kwargs):
1616
"""Init options from Django settings"""
17-
self.api_key = get_anymail_setting('MAILGUN_API_KEY', allow_bare=True)
18-
api_url = get_anymail_setting("MAILGUN_API_URL", "https://api.mailgun.net/v3")
17+
esp_name = self.esp_name
18+
self.api_key = get_anymail_setting('api_key', esp_name=esp_name, kwargs=kwargs, allow_bare=True)
19+
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
20+
default="https://api.mailgun.net/v3")
1921
if not api_url.endswith("/"):
2022
api_url += "/"
2123
super(MailgunBackend, self).__init__(api_url, **kwargs)

anymail/backends/mandrill.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ class MandrillBackend(AnymailRequestsBackend):
1414

1515
def __init__(self, **kwargs):
1616
"""Init options from Django settings"""
17-
self.api_key = get_anymail_setting('MANDRILL_API_KEY', allow_bare=True)
18-
api_url = get_anymail_setting("MANDRILL_API_URL", "https://mandrillapp.com/api/1.0")
17+
esp_name = self.esp_name
18+
self.api_key = get_anymail_setting('api_key', esp_name=esp_name, kwargs=kwargs, allow_bare=True)
19+
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
20+
default="https://mandrillapp.com/api/1.0")
1921
if not api_url.endswith("/"):
2022
api_url += "/"
2123
super(MandrillBackend, self).__init__(api_url, **kwargs)

anymail/backends/postmark.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ class PostmarkBackend(AnymailRequestsBackend):
1414

1515
def __init__(self, **kwargs):
1616
"""Init options from Django settings"""
17-
self.server_token = get_anymail_setting('POSTMARK_SERVER_TOKEN', allow_bare=True)
18-
api_url = get_anymail_setting("POSTMARK_API_URL", "https://api.postmarkapp.com/")
17+
esp_name = self.esp_name
18+
self.server_token = get_anymail_setting('server_token', esp_name=esp_name, kwargs=kwargs, allow_bare=True)
19+
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
20+
default="https://api.postmarkapp.com/")
1921
if not api_url.endswith("/"):
2022
api_url += "/"
2123
super(PostmarkBackend, self).__init__(api_url, **kwargs)

anymail/backends/sendgrid.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
from email.utils import unquote
22

3-
from django.core.exceptions import ImproperlyConfigured
43
from django.core.mail import make_msgid
54
from requests.structures import CaseInsensitiveDict
65

7-
from ..exceptions import AnymailRequestsAPIError
6+
from ..exceptions import AnymailConfigurationError, AnymailRequestsAPIError
87
from ..message import AnymailRecipientStatus
98
from ..utils import get_anymail_setting, timestamp
109

@@ -19,19 +18,25 @@ class SendGridBackend(AnymailRequestsBackend):
1918
def __init__(self, **kwargs):
2019
"""Init options from Django settings"""
2120
# Auth requires *either* SENDGRID_API_KEY or SENDGRID_USERNAME+SENDGRID_PASSWORD
22-
self.api_key = get_anymail_setting('SENDGRID_API_KEY', default=None, allow_bare=True)
23-
self.username = get_anymail_setting('SENDGRID_USERNAME', default=None, allow_bare=True)
24-
self.password = get_anymail_setting('SENDGRID_PASSWORD', default=None, allow_bare=True)
25-
if self.api_key is None and self.username is None and self.password is None:
26-
raise ImproperlyConfigured(
21+
esp_name = self.esp_name
22+
self.api_key = get_anymail_setting('api_key', esp_name=esp_name, kwargs=kwargs,
23+
default=None, allow_bare=True)
24+
self.username = get_anymail_setting('username', esp_name=esp_name, kwargs=kwargs,
25+
default=None, allow_bare=True)
26+
self.password = get_anymail_setting('password', esp_name=esp_name, kwargs=kwargs,
27+
default=None, allow_bare=True)
28+
if self.api_key is None and (self.username is None or self.password is None):
29+
raise AnymailConfigurationError(
2730
"You must set either SENDGRID_API_KEY or both SENDGRID_USERNAME and "
2831
"SENDGRID_PASSWORD in your Django ANYMAIL settings."
2932
)
3033

31-
self.generate_message_id = get_anymail_setting('SENDGRID_GENERATE_MESSAGE_ID', default=True)
34+
self.generate_message_id = get_anymail_setting('generate_message_id', esp_name=esp_name,
35+
kwargs=kwargs, default=True)
3236

3337
# This is SendGrid's Web API v2 (because the Web API v3 doesn't support sending)
34-
api_url = get_anymail_setting("SENDGRID_API_URL", "https://api.sendgrid.com/api/")
38+
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
39+
default="https://api.sendgrid.com/api/")
3540
if not api_url.endswith("/"):
3641
api_url += "/"
3742
super(SendGridBackend, self).__init__(api_url, **kwargs)

anymail/exceptions.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,15 @@ def __init__(self, message=None, orig_err=None, *args, **kwargs):
125125
super(AnymailSerializationError, self).__init__(message, *args, **kwargs)
126126

127127

128-
# This deliberately doesn't inherit from AnymailError
129-
class AnymailImproperlyInstalled(ImproperlyConfigured, ImportError):
128+
class AnymailConfigurationError(ImproperlyConfigured):
129+
"""Exception for Anymail configuration or installation issues"""
130+
# This deliberately doesn't inherit from AnymailError,
131+
# because we don't want it to be swallowed by backend fail_silently
132+
133+
134+
class AnymailImproperlyInstalled(AnymailConfigurationError, ImportError):
135+
"""Exception for Anymail missing package dependencies"""
136+
130137
def __init__(self, missing_package, backend="<backend>"):
131138
message = "The %s package is required to use this backend, but isn't installed.\n" \
132139
"(Be sure to use `pip install django-anymail[%s]` " \

anymail/utils.py

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77

88
import six
99
from django.conf import settings
10-
from django.core.exceptions import ImproperlyConfigured
1110
from django.core.mail.message import sanitize_address, DEFAULT_ATTACHMENT_MIME_TYPE
1211
from django.utils.timezone import utc
1312

13+
from .exceptions import AnymailConfigurationError
1414

1515
UNSET = object() # Used as non-None default value
1616

@@ -158,25 +158,42 @@ def get_content_disposition(mimeobj):
158158
return str(value).partition(';')[0].strip().lower()
159159

160160

161-
def get_anymail_setting(setting, default=UNSET, allow_bare=False):
162-
"""Returns a Django Anymail setting.
161+
def get_anymail_setting(name, default=UNSET, esp_name=None, kwargs=None, allow_bare=False):
162+
"""Returns an Anymail option from kwargs or Django settings.
163163
164164
Returns first of:
165-
- settings.ANYMAIL[setting]
166-
- settings.ANYMAIL_<setting>
167-
- settings.<setting> (only if allow_bare)
168-
- default if provided; else raises ImproperlyConfigured
165+
- kwargs[name] -- e.g., kwargs['api_key'] -- and name key will be popped from kwargs
166+
- settings.ANYMAIL['<ESP_NAME>_<NAME>'] -- e.g., settings.ANYMAIL['MAILGUN_API_KEY']
167+
- settings.ANYMAIL_<ESP_NAME>_<NAME> -- e.g., settings.ANYMAIL_MAILGUN_API_KEY
168+
- settings.<ESP_NAME>_<NAME> (only if allow_bare) -- e.g., settings.MAILGUN_API_KEY
169+
- default if provided; else raises AnymailConfigurationError
169170
170-
ANYMAIL = { "MAILGUN_SEND_DEFAULTS" : { ... }, ... }
171-
ANYMAIL_MAILGUN_SEND_DEFAULTS = { ... }
172-
173-
If allow_bare, allows settings.<setting> without the ANYMAIL_ prefix:
171+
If allow_bare, allows settings.<ESP_NAME>_<NAME> without the ANYMAIL_ prefix:
174172
ANYMAIL = { "MAILGUN_API_KEY": "xyz", ... }
175173
ANYMAIL_MAILGUN_API_KEY = "xyz"
176174
MAILGUN_API_KEY = "xyz"
177175
"""
178176

177+
try:
178+
value = kwargs.pop(name)
179+
if name in ['username', 'password']:
180+
# Work around a problem in django.core.mail.send_mail, which calls
181+
# get_connection(... username=None, password=None) by default.
182+
# We need to ignore those None defaults (else settings like
183+
# 'SENDGRID_USERNAME' get unintentionally overridden from kwargs).
184+
if value is not None:
185+
return value
186+
else:
187+
return value
188+
except (AttributeError, KeyError):
189+
pass
190+
191+
if esp_name is not None:
192+
setting = "{}_{}".format(esp_name.upper(), name.upper())
193+
else:
194+
setting = name.upper()
179195
anymail_setting = "ANYMAIL_%s" % setting
196+
180197
try:
181198
return settings.ANYMAIL[setting]
182199
except (AttributeError, KeyError):
@@ -193,7 +210,7 @@ def get_anymail_setting(setting, default=UNSET, allow_bare=False):
193210
if allow_bare:
194211
message += " or %s" % setting
195212
message += " in your Django settings"
196-
raise ImproperlyConfigured(message)
213+
raise AnymailConfigurationError(message)
197214
else:
198215
return default
199216

docs/installation.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,14 @@ if you are using other Django apps that work with the same ESP.)
122122
# nor ANYMAIL_MAILGUN_API_KEY have been set
123123
124124
125+
Finally, for complex use cases, you can override most settings on a per-instance
126+
basis by providing keyword args where the instance is initialized (e.g., in a
127+
:func:`~django.core.mail.get_connection` call to create an email backend instance,
128+
or in `View.as_view()` call to set up webhooks in a custom urls.py). To get the kwargs
129+
parameter for a setting, drop "ANYMAIL" and the ESP name, and lowercase the rest:
130+
e.g., you can override ANYMAIL_MAILGUN_API_KEY by passing `api_key="abc"` to
131+
:func:`~django.core.mail.get_connection`. See :ref:`multiple-backends` for an example.
132+
125133
There are specific Anymail settings for each ESP (like API keys and urls).
126134
See the :ref:`supported ESPs <supported-esps>` section for details.
127135
Here are the other settings Anymail supports:

docs/tips/multiple_backends.rst

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ This could be useful, for example, to deliver customer emails with the ESP,
1313
but send admin emails directly through an SMTP server:
1414

1515
.. code-block:: python
16-
:emphasize-lines: 8,10,13,15
16+
:emphasize-lines: 8,10,13,15,19-20,22
1717
1818
from django.core.mail import send_mail, get_connection
1919
@@ -28,9 +28,17 @@ but send admin emails directly through an SMTP server:
2828
2929
# You can even use multiple Anymail backends in the same app:
3030
sendgrid_backend = get_connection('anymail.backends.sendgrid.SendGridBackend')
31-
send_mail("Password reset", "Here you go", "user@example.com", ["noreply@example.com"],
31+
send_mail("Password reset", "Here you go", "noreply@example.com", ["user@example.com"],
3232
connection=sendgrid_backend)
3333
34+
# You can override settings.py settings with kwargs to get_connection.
35+
# This example supplies credentials to use a SendGrid subuser acccount:
36+
alt_sendgrid_backend = get_connection('anymail.backends.sendgrid.SendGridBackend',
37+
username='marketing_subuser', password='abc123')
38+
send_mail("Here's that info", "you wanted", "[email protected]", ["[email protected]"],
39+
connection=alt_sendgrid_backend)
40+
41+
3442
You can supply a different connection to Django's
3543
:func:`~django.core.mail.send_mail` and :func:`~django.core.mail.send_mass_mail` helpers,
3644
and in the constructor for an
@@ -39,6 +47,3 @@ and in the constructor for an
3947

4048
(See the :class:`django.utils.log.AdminEmailHandler` docs for more information
4149
on Django's admin error logging.)
42-
43-
.. _django.utils.log.AdminEmailHandler:
44-
https://docs.djangoproject.com/en/stable/topics/logging/#django.utils.log.AdminEmailHandler

tests/test_general_backend.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from django.core.mail import get_connection
2+
from django.test import SimpleTestCase
3+
from django.test.utils import override_settings
4+
5+
from .utils import AnymailTestMixin
6+
7+
8+
class BackendSettingsTests(SimpleTestCase, AnymailTestMixin):
9+
"""Test settings initializations for Anymail EmailBackends"""
10+
11+
# We should add a "GenericBackend" or something basic for testing.
12+
# For now, we just access real backends directly.
13+
14+
@override_settings(ANYMAIL={'MAILGUN_API_KEY': 'api_key_from_settings'})
15+
def test_connection_kwargs_overrides_settings(self):
16+
connection = get_connection('anymail.backends.mailgun.MailgunBackend')
17+
self.assertEqual(connection.api_key, 'api_key_from_settings')
18+
19+
connection = get_connection('anymail.backends.mailgun.MailgunBackend',
20+
api_key='api_key_from_kwargs')
21+
self.assertEqual(connection.api_key, 'api_key_from_kwargs')
22+
23+
@override_settings(ANYMAIL={'SENDGRID_USERNAME': 'username_from_settings',
24+
'SENDGRID_PASSWORD': 'password_from_settings'})
25+
def test_username_password_kwargs_overrides(self):
26+
# Additional checks for username and password, which are special-cased
27+
# because of Django core mail function defaults.
28+
connection = get_connection('anymail.backends.sendgrid.SendGridBackend')
29+
self.assertEqual(connection.username, 'username_from_settings')
30+
self.assertEqual(connection.password, 'password_from_settings')
31+
32+
connection = get_connection('anymail.backends.sendgrid.SendGridBackend',
33+
username='username_from_kwargs', password='password_from_kwargs')
34+
self.assertEqual(connection.username, 'username_from_kwargs')
35+
self.assertEqual(connection.password, 'password_from_kwargs')

0 commit comments

Comments
 (0)