Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_success_send():
responses.add(
responses.POST,
'https://api.sparkpost.com/api/v1/transmissions',
status=200,
content_type='application/json',
body='{"results": "yay"}'
)
sp = SparkPost('fake-key')
results = sp.transmission.send()
assert results == 'yay'
def test_fail_domains():
responses.add(
responses.GET,
'https://api.sparkpost.com/api/v1/metrics/domains',
status=500,
content_type='application/json',
body="""
{"errors": [{"message": "You failed", "description": "More Info"}]}
"""
)
with pytest.raises(SparkPostAPIException):
sp = SparkPost('fake-key')
sp.metrics.domains.list()
def test_success_list():
responses.add(
responses.GET,
base_uri,
status=200,
content_type='application/json',
body='{"results": []}'
)
sp = SparkPost('fake-key')
results = sp.sending_domains.list()
assert results == []
def test_success_delete():
responses.add(
responses.DELETE,
'https://api.sparkpost.com/api/v1/suppression-list/foobar',
status=204,
content_type='application/json'
)
sp = SparkPost('fake-key')
results = sp.suppression_list.delete('foobar')
assert results is True
import os
from sparkpost import SparkPost
parent_dir = os.path.dirname(os.path.realpath(__file__))
attachment_path = os.path.abspath(os.path.join(parent_dir, "a-file.txt"))
sp = SparkPost()
response = sp.transmissions.send(
recipients=[
'postmaster@example.com',
'you@me.com',
{
'address': {
'email': 'john.doe@example.com',
'name': 'John Doe'
}
}
],
cc=['carboncopy@example.com'],
bcc=['blindcarboncopy@example.com'],
html='<p>Hello {{name}}</p>',
text='Hello {{name}}',
super(EmailBackend, self).__init__(**kwargs)
# SPARKPOST_API_KEY is optional - library reads from env by default
self.api_key = get_anymail_setting('api_key', esp_name=self.esp_name,
kwargs=kwargs, allow_bare=True, default=None)
# SPARKPOST_API_URL is optional - default is set by library;
# if provided, must be a full SparkPost API endpoint, including "/v1" if appropriate
api_url = get_anymail_setting('api_url', esp_name=self.esp_name, kwargs=kwargs, default=None)
extra_sparkpost_params = {}
if api_url is not None:
if api_url.endswith("/"):
api_url = api_url[:-1]
extra_sparkpost_params['base_uri'] = _FullSparkPostEndpoint(api_url)
try:
self.sp = SparkPost(self.api_key, **extra_sparkpost_params) # SparkPost API instance
except SparkPostException as err:
# This is almost certainly a missing API key
raise AnymailConfigurationError(
"Error initializing SparkPost: %s\n"
"You may need to set ANYMAIL = {'SPARKPOST_API_KEY': ...} "
"or ANYMAIL_SPARKPOST_API_KEY in your Django settings, "
"or SPARKPOST_API_KEY in your environment." % str(err)
)
"""
This script demonstrates how to use the SparkPostAPIException class. This
particular example will yield output similar to the following:
$ python send_transmission_exception.py
400
{u'errors': [{u'message': u'Invalid domain', u'code': u'7001', u'description':
u'Unconfigured Sending Domain '}]}
['Invalid domain Code: 7001 Description: Unconfigured Sending Domain
\n']
"""
from sparkpost import SparkPost
from sparkpost.exceptions import SparkPostAPIException
sp = SparkPost()
try:
response = sp.transmissions.send(
recipients=['john.doe@example.com'],
text='Hello there',
from_email='Testing ',
subject='Testing python-sparkpost exceptions'
)
except SparkPostAPIException as err:
# http response status code
print(err.status)
# python requests library response object
# http://docs.python-requests.org/en/master/api/#requests.Response
print(err.response.json())
# list of formatted errors
print(err.errors)
%s
'''
html = html_template % (subject, message)
if not app.config.get('TESTING'):
# only send email to admins if it's a pending request
if email_admins:
email_addresses = [app.config['ADMIN_EMAIL']]
else:
email_addresses = [user.email]
if email_addresses:
sp = SparkPost(app.config['SPARKPOST_API_KEY'])
sp.transmissions.send(
from_email=app.config['ADMIN_EMAIL'],
subject=subject,
recipients=email_addresses,
html=html
)
import sparkpost
from .exceptions import SparkPostAPIException
from .base import TornadoTransport
from .transmissions import Transmissions
__all__ = ["SparkPost", "TornadoTransport", "SparkPostAPIException",
"Transmissions"]
class SparkPost(sparkpost.SparkPost):
TRANSPORT_CLASS = TornadoTransport
def __init__(self, *args, **kwargs):
super(SparkPost, self).__init__(*args, **kwargs)
self.transmissions = Transmissions(self.base_uri, self.api_key,
self.TRANSPORT_CLASS)
self.transmission = self.transmissions
from sparkpost import SparkPost
sp = SparkPost()
sub_data = {
'first_name': 'John',
'last_name': 'Doe'
}
template = sp.templates.preview('template_id', sub_data, True)
print(template)