Reformat code with automated tools

Apply standardized code style
This commit is contained in:
medmunds
2023-02-06 12:27:43 -08:00
committed by Mike Edmunds
parent 40891fcb4a
commit b4e22c63b3
94 changed files with 12936 additions and 7443 deletions

View File

@@ -1,7 +1,7 @@
from .base_requests import AnymailRequestsBackend, RequestsPayload
from ..exceptions import AnymailRequestsAPIError
from ..message import AnymailRecipientStatus
from ..utils import get_anymail_setting, update_deep
from .base_requests import AnymailRequestsBackend, RequestsPayload
class EmailBackend(AnymailRequestsBackend):
@@ -13,12 +13,18 @@ class EmailBackend(AnymailRequestsBackend):
def __init__(self, **kwargs):
"""Init options from Django settings"""
self.api_key = get_anymail_setting('api_key', esp_name=self.esp_name,
kwargs=kwargs, allow_bare=True)
self.subaccount = get_anymail_setting('subaccount', esp_name=self.esp_name,
kwargs=kwargs, default=None)
api_url = get_anymail_setting('api_url', esp_name=self.esp_name, kwargs=kwargs,
default="https://api.sparkpost.com/api/v1/")
self.api_key = get_anymail_setting(
"api_key", esp_name=self.esp_name, kwargs=kwargs, allow_bare=True
)
self.subaccount = get_anymail_setting(
"subaccount", esp_name=self.esp_name, kwargs=kwargs, default=None
)
api_url = get_anymail_setting(
"api_url",
esp_name=self.esp_name,
kwargs=kwargs,
default="https://api.sparkpost.com/api/v1/",
)
if not api_url.endswith("/"):
api_url += "/"
super().__init__(api_url, **kwargs)
@@ -34,9 +40,13 @@ class EmailBackend(AnymailRequestsBackend):
rejected = results["total_rejected_recipients"]
transmission_id = results["id"]
except (KeyError, TypeError) as err:
raise AnymailRequestsAPIError("Invalid SparkPost API response format",
email_message=message, payload=payload,
response=response, backend=self) from err
raise AnymailRequestsAPIError(
"Invalid SparkPost API response format",
email_message=message,
payload=payload,
response=response,
backend=self,
) from err
# SparkPost doesn't (yet*) tell us *which* recipients were accepted or rejected.
# (* looks like undocumented 'rcpt_to_errors' might provide this info.)
@@ -44,26 +54,32 @@ class EmailBackend(AnymailRequestsBackend):
# else just report 'unknown' for all recipients.
recipient_count = len(payload.recipients)
if accepted == recipient_count and rejected == 0:
status = 'queued'
status = "queued"
elif rejected == recipient_count and accepted == 0:
status = 'rejected'
status = "rejected"
else: # mixed results, or wrong total
status = 'unknown'
recipient_status = AnymailRecipientStatus(message_id=transmission_id, status=status)
return {recipient.addr_spec: recipient_status for recipient in payload.recipients}
status = "unknown"
recipient_status = AnymailRecipientStatus(
message_id=transmission_id, status=status
)
return {
recipient.addr_spec: recipient_status for recipient in payload.recipients
}
class SparkPostPayload(RequestsPayload):
def __init__(self, message, defaults, backend, *args, **kwargs):
http_headers = {
'Authorization': backend.api_key,
'Content-Type': 'application/json',
"Authorization": backend.api_key,
"Content-Type": "application/json",
}
if backend.subaccount is not None:
http_headers['X-MSYS-SUBACCOUNT'] = backend.subaccount
http_headers["X-MSYS-SUBACCOUNT"] = backend.subaccount
self.recipients = [] # all recipients, for backend parse_recipient_status
self.cc_and_bcc = [] # for _finalize_recipients
super().__init__(message, defaults, backend, headers=http_headers, *args, **kwargs)
super().__init__(
message, defaults, backend, headers=http_headers, *args, **kwargs
)
def get_api_endpoint(self):
return "transmissions/"
@@ -74,15 +90,15 @@ class SparkPostPayload(RequestsPayload):
def _finalize_recipients(self):
# https://www.sparkpost.com/docs/faq/cc-bcc-with-rest-api/
# self.data["recipients"] is currently a list of all to-recipients. We need to add
# all cc and bcc recipients. Exactly how depends on whether this is a batch send.
# self.data["recipients"] is currently a list of all to-recipients. Must add all
# cc and bcc recipients. Exactly how depends on whether this is a batch send.
if self.is_batch():
# For batch sends, must duplicate the cc/bcc for *every* to-recipient
# (using each to-recipient's metadata and substitutions).
extra_recipients = []
for to_recipient in self.data["recipients"]:
for email in self.cc_and_bcc:
extra = to_recipient.copy() # capture "metadata" and "substitutions", if any
extra = to_recipient.copy() # gets "metadata" and "substitutions"
extra["address"] = {
"email": email.addr_spec,
"header_to": to_recipient["address"]["header_to"],
@@ -94,17 +110,21 @@ class SparkPostPayload(RequestsPayload):
# "To" header to show all the "To" recipients...
full_to_header = ", ".join(
to_recipient["address"]["header_to"]
for to_recipient in self.data["recipients"])
for to_recipient in self.data["recipients"]
)
for recipient in self.data["recipients"]:
recipient["address"]["header_to"] = full_to_header
# ... and then simply add the cc/bcc to the end of the list.
# (There is no per-recipient data, or it would be a batch send.)
self.data["recipients"].extend(
{"address": {
"email": email.addr_spec,
"header_to": full_to_header,
}}
for email in self.cc_and_bcc)
{
"address": {
"email": email.addr_spec,
"header_to": full_to_header,
}
}
for email in self.cc_and_bcc
)
#
# Payload construction
@@ -127,11 +147,14 @@ class SparkPostPayload(RequestsPayload):
# (We use "header_to" rather than "name" to simplify some logic
# in _finalize_recipients; the results end up the same.)
self.data["recipients"].extend(
{"address": {
"email": email.addr_spec,
"header_to": email.address,
}}
for email in emails)
{
"address": {
"email": email.addr_spec,
"header_to": email.address,
}
}
for email in emails
)
self.recipients += emails
def set_cc(self, emails):
@@ -155,7 +178,9 @@ class SparkPostPayload(RequestsPayload):
def set_reply_to(self, emails):
if emails:
self.data["content"]["reply_to"] = ", ".join(email.address for email in emails)
self.data["content"]["reply_to"] = ", ".join(
email.address for email in emails
)
def set_extra_headers(self, headers):
if headers:
@@ -166,7 +191,8 @@ class SparkPostPayload(RequestsPayload):
def set_html_body(self, body):
if "html" in self.data["content"]:
# second html body could show up through multiple alternatives, or html body + alternative
# second html body could show up through multiple alternatives,
# or html body + alternative
self.unsupported_feature("multiple html parts")
self.data["content"]["html"] = body
@@ -179,19 +205,27 @@ class SparkPostPayload(RequestsPayload):
super().add_alternative(content, mimetype)
def set_attachments(self, atts):
attachments = [{
"name": att.name or "",
"type": att.content_type,
"data": att.b64content,
} for att in atts if not att.inline]
attachments = [
{
"name": att.name or "",
"type": att.content_type,
"data": att.b64content,
}
for att in atts
if not att.inline
]
if attachments:
self.data["content"]["attachments"] = attachments
inline_images = [{
"name": att.cid,
"type": att.mimetype,
"data": att.b64content,
} for att in atts if att.inline]
inline_images = [
{
"name": att.cid,
"type": att.mimetype,
"data": att.b64content,
}
for att in atts
if att.inline
]
if inline_images:
self.data["content"]["inline_images"] = inline_images