mirror of
https://github.com/pacnpal/django-anymail.git
synced 2025-12-20 03:41:05 -05:00
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
This commit is contained in:
@@ -17,12 +17,15 @@ class AnymailBaseBackend(BaseEmailBackend):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(AnymailBaseBackend, self).__init__(*args, **kwargs)
|
||||
|
||||
self.ignore_unsupported_features = get_anymail_setting("IGNORE_UNSUPPORTED_FEATURES", False)
|
||||
self.ignore_recipient_status = get_anymail_setting("IGNORE_RECIPIENT_STATUS", False)
|
||||
self.ignore_unsupported_features = get_anymail_setting('ignore_unsupported_features',
|
||||
kwargs=kwargs, default=False)
|
||||
self.ignore_recipient_status = get_anymail_setting('ignore_recipient_status',
|
||||
kwargs=kwargs, default=False)
|
||||
|
||||
# Merge SEND_DEFAULTS and <esp_name>_SEND_DEFAULTS settings
|
||||
send_defaults = get_anymail_setting("SEND_DEFAULTS", {})
|
||||
esp_send_defaults = get_anymail_setting("%s_SEND_DEFAULTS" % self.esp_name.upper(), None)
|
||||
send_defaults = get_anymail_setting('send_defaults', default={}) # but not from kwargs
|
||||
esp_send_defaults = get_anymail_setting('send_defaults', esp_name=self.esp_name,
|
||||
kwargs=kwargs, default=None)
|
||||
if esp_send_defaults is not None:
|
||||
send_defaults = send_defaults.copy()
|
||||
send_defaults.update(esp_send_defaults)
|
||||
|
||||
@@ -14,8 +14,10 @@ class MailgunBackend(AnymailRequestsBackend):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
"""Init options from Django settings"""
|
||||
self.api_key = get_anymail_setting('MAILGUN_API_KEY', allow_bare=True)
|
||||
api_url = get_anymail_setting("MAILGUN_API_URL", "https://api.mailgun.net/v3")
|
||||
esp_name = self.esp_name
|
||||
self.api_key = get_anymail_setting('api_key', esp_name=esp_name, kwargs=kwargs, allow_bare=True)
|
||||
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
|
||||
default="https://api.mailgun.net/v3")
|
||||
if not api_url.endswith("/"):
|
||||
api_url += "/"
|
||||
super(MailgunBackend, self).__init__(api_url, **kwargs)
|
||||
|
||||
@@ -14,8 +14,10 @@ class MandrillBackend(AnymailRequestsBackend):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
"""Init options from Django settings"""
|
||||
self.api_key = get_anymail_setting('MANDRILL_API_KEY', allow_bare=True)
|
||||
api_url = get_anymail_setting("MANDRILL_API_URL", "https://mandrillapp.com/api/1.0")
|
||||
esp_name = self.esp_name
|
||||
self.api_key = get_anymail_setting('api_key', esp_name=esp_name, kwargs=kwargs, allow_bare=True)
|
||||
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
|
||||
default="https://mandrillapp.com/api/1.0")
|
||||
if not api_url.endswith("/"):
|
||||
api_url += "/"
|
||||
super(MandrillBackend, self).__init__(api_url, **kwargs)
|
||||
|
||||
@@ -14,8 +14,10 @@ class PostmarkBackend(AnymailRequestsBackend):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
"""Init options from Django settings"""
|
||||
self.server_token = get_anymail_setting('POSTMARK_SERVER_TOKEN', allow_bare=True)
|
||||
api_url = get_anymail_setting("POSTMARK_API_URL", "https://api.postmarkapp.com/")
|
||||
esp_name = self.esp_name
|
||||
self.server_token = get_anymail_setting('server_token', esp_name=esp_name, kwargs=kwargs, allow_bare=True)
|
||||
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
|
||||
default="https://api.postmarkapp.com/")
|
||||
if not api_url.endswith("/"):
|
||||
api_url += "/"
|
||||
super(PostmarkBackend, self).__init__(api_url, **kwargs)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
from email.utils import unquote
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.mail import make_msgid
|
||||
from requests.structures import CaseInsensitiveDict
|
||||
|
||||
from ..exceptions import AnymailRequestsAPIError
|
||||
from ..exceptions import AnymailConfigurationError, AnymailRequestsAPIError
|
||||
from ..message import AnymailRecipientStatus
|
||||
from ..utils import get_anymail_setting, timestamp
|
||||
|
||||
@@ -19,19 +18,25 @@ class SendGridBackend(AnymailRequestsBackend):
|
||||
def __init__(self, **kwargs):
|
||||
"""Init options from Django settings"""
|
||||
# Auth requires *either* SENDGRID_API_KEY or SENDGRID_USERNAME+SENDGRID_PASSWORD
|
||||
self.api_key = get_anymail_setting('SENDGRID_API_KEY', default=None, allow_bare=True)
|
||||
self.username = get_anymail_setting('SENDGRID_USERNAME', default=None, allow_bare=True)
|
||||
self.password = get_anymail_setting('SENDGRID_PASSWORD', default=None, allow_bare=True)
|
||||
if self.api_key is None and self.username is None and self.password is None:
|
||||
raise ImproperlyConfigured(
|
||||
esp_name = self.esp_name
|
||||
self.api_key = get_anymail_setting('api_key', esp_name=esp_name, kwargs=kwargs,
|
||||
default=None, allow_bare=True)
|
||||
self.username = get_anymail_setting('username', esp_name=esp_name, kwargs=kwargs,
|
||||
default=None, allow_bare=True)
|
||||
self.password = get_anymail_setting('password', esp_name=esp_name, kwargs=kwargs,
|
||||
default=None, allow_bare=True)
|
||||
if self.api_key is None and (self.username is None or self.password is None):
|
||||
raise AnymailConfigurationError(
|
||||
"You must set either SENDGRID_API_KEY or both SENDGRID_USERNAME and "
|
||||
"SENDGRID_PASSWORD in your Django ANYMAIL settings."
|
||||
)
|
||||
|
||||
self.generate_message_id = get_anymail_setting('SENDGRID_GENERATE_MESSAGE_ID', default=True)
|
||||
self.generate_message_id = get_anymail_setting('generate_message_id', esp_name=esp_name,
|
||||
kwargs=kwargs, default=True)
|
||||
|
||||
# This is SendGrid's Web API v2 (because the Web API v3 doesn't support sending)
|
||||
api_url = get_anymail_setting("SENDGRID_API_URL", "https://api.sendgrid.com/api/")
|
||||
api_url = get_anymail_setting('api_url', esp_name=esp_name, kwargs=kwargs,
|
||||
default="https://api.sendgrid.com/api/")
|
||||
if not api_url.endswith("/"):
|
||||
api_url += "/"
|
||||
super(SendGridBackend, self).__init__(api_url, **kwargs)
|
||||
|
||||
@@ -125,8 +125,15 @@ class AnymailSerializationError(AnymailError, TypeError):
|
||||
super(AnymailSerializationError, self).__init__(message, *args, **kwargs)
|
||||
|
||||
|
||||
# This deliberately doesn't inherit from AnymailError
|
||||
class AnymailImproperlyInstalled(ImproperlyConfigured, ImportError):
|
||||
class AnymailConfigurationError(ImproperlyConfigured):
|
||||
"""Exception for Anymail configuration or installation issues"""
|
||||
# This deliberately doesn't inherit from AnymailError,
|
||||
# because we don't want it to be swallowed by backend fail_silently
|
||||
|
||||
|
||||
class AnymailImproperlyInstalled(AnymailConfigurationError, ImportError):
|
||||
"""Exception for Anymail missing package dependencies"""
|
||||
|
||||
def __init__(self, missing_package, backend="<backend>"):
|
||||
message = "The %s package is required to use this backend, but isn't installed.\n" \
|
||||
"(Be sure to use `pip install django-anymail[%s]` " \
|
||||
|
||||
@@ -7,10 +7,10 @@ from time import mktime
|
||||
|
||||
import six
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.mail.message import sanitize_address, DEFAULT_ATTACHMENT_MIME_TYPE
|
||||
from django.utils.timezone import utc
|
||||
|
||||
from .exceptions import AnymailConfigurationError
|
||||
|
||||
UNSET = object() # Used as non-None default value
|
||||
|
||||
@@ -158,25 +158,42 @@ def get_content_disposition(mimeobj):
|
||||
return str(value).partition(';')[0].strip().lower()
|
||||
|
||||
|
||||
def get_anymail_setting(setting, default=UNSET, allow_bare=False):
|
||||
"""Returns a Django Anymail setting.
|
||||
def get_anymail_setting(name, default=UNSET, esp_name=None, kwargs=None, allow_bare=False):
|
||||
"""Returns an Anymail option from kwargs or Django settings.
|
||||
|
||||
Returns first of:
|
||||
- settings.ANYMAIL[setting]
|
||||
- settings.ANYMAIL_<setting>
|
||||
- settings.<setting> (only if allow_bare)
|
||||
- default if provided; else raises ImproperlyConfigured
|
||||
- kwargs[name] -- e.g., kwargs['api_key'] -- and name key will be popped from kwargs
|
||||
- settings.ANYMAIL['<ESP_NAME>_<NAME>'] -- e.g., settings.ANYMAIL['MAILGUN_API_KEY']
|
||||
- settings.ANYMAIL_<ESP_NAME>_<NAME> -- e.g., settings.ANYMAIL_MAILGUN_API_KEY
|
||||
- settings.<ESP_NAME>_<NAME> (only if allow_bare) -- e.g., settings.MAILGUN_API_KEY
|
||||
- default if provided; else raises AnymailConfigurationError
|
||||
|
||||
ANYMAIL = { "MAILGUN_SEND_DEFAULTS" : { ... }, ... }
|
||||
ANYMAIL_MAILGUN_SEND_DEFAULTS = { ... }
|
||||
|
||||
If allow_bare, allows settings.<setting> without the ANYMAIL_ prefix:
|
||||
If allow_bare, allows settings.<ESP_NAME>_<NAME> without the ANYMAIL_ prefix:
|
||||
ANYMAIL = { "MAILGUN_API_KEY": "xyz", ... }
|
||||
ANYMAIL_MAILGUN_API_KEY = "xyz"
|
||||
MAILGUN_API_KEY = "xyz"
|
||||
"""
|
||||
|
||||
try:
|
||||
value = kwargs.pop(name)
|
||||
if name in ['username', 'password']:
|
||||
# Work around a problem in django.core.mail.send_mail, which calls
|
||||
# get_connection(... username=None, password=None) by default.
|
||||
# We need to ignore those None defaults (else settings like
|
||||
# 'SENDGRID_USERNAME' get unintentionally overridden from kwargs).
|
||||
if value is not None:
|
||||
return value
|
||||
else:
|
||||
return value
|
||||
except (AttributeError, KeyError):
|
||||
pass
|
||||
|
||||
if esp_name is not None:
|
||||
setting = "{}_{}".format(esp_name.upper(), name.upper())
|
||||
else:
|
||||
setting = name.upper()
|
||||
anymail_setting = "ANYMAIL_%s" % setting
|
||||
|
||||
try:
|
||||
return settings.ANYMAIL[setting]
|
||||
except (AttributeError, KeyError):
|
||||
@@ -193,7 +210,7 @@ def get_anymail_setting(setting, default=UNSET, allow_bare=False):
|
||||
if allow_bare:
|
||||
message += " or %s" % setting
|
||||
message += " in your Django settings"
|
||||
raise ImproperlyConfigured(message)
|
||||
raise AnymailConfigurationError(message)
|
||||
else:
|
||||
return default
|
||||
|
||||
|
||||
Reference in New Issue
Block a user