Skip to content

Commit

Permalink
Merge pull request #40 from aydrian/ISSUE-14
Browse files Browse the repository at this point in the history
Added Templates resource lib
  • Loading branch information
richleland committed Aug 25, 2015
2 parents d2af4f9 + 28a7278 commit 4f37988
Show file tree
Hide file tree
Showing 15 changed files with 530 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,6 @@ venv/

# autoenv
.env

# Mac OSX
.DS_Store
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ Core contributors
-----------------

- Bob Evans <bob.evans@messagesystems.com> `@bizob2828 <https://github.com/bizob2828>`_
- Aydrian Howard <aydrian.howard@messagesystems.com> `@aydrian <https://github.com/aydrian>`_
- Rich Leland <rich.leland@messagesystems.com> `@richleland <https://github.com/richleland>`_


Expand Down
7 changes: 7 additions & 0 deletions docs/api/templates.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.. module:: sparkpost.templates

:mod:`sparkpost.templates`
=============================

.. autoclass:: Templates
:members:
4 changes: 2 additions & 2 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Alternatively, you can pass the API key to the SparkPost class:
from sparkpost import SparkPost
sp = SparkPost('YOUR API KEY')
.. _API & SMTP: https://app.sparkpost.com/configuration/credentials


Expand All @@ -45,6 +45,7 @@ The following resources are available in python-sparkpost:
:maxdepth: 1

resources/metrics
resources/templates
resources/transmissions


Expand Down Expand Up @@ -77,4 +78,3 @@ Contribute

.. _`the repository`: http://github.com/SparkPost/python-sparkpost
.. _AUTHORS: https://github.com/SparkPost/python-sparkpost/blob/master/AUTHORS.rst

69 changes: 69 additions & 0 deletions docs/resources/templates.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
Templates
=============

Let's use the underlying `templates API`_ to create a template:

.. code-block:: python
from sparkpost import SparkPost
sp = SparkPost()
response = sp.templates.create(
id='TEST_ID',
name='Test Template',
from_email='test@test.com',
subject='Test email template!',
html='<b>This is a test email template!</b>'
)
print response
# outputs {u'id': u'TEST_ID'}
.. _templates API: https://www.sparkpost.com/api#/reference/templates


Retrieve a template
-----------------------

.. code-block:: python
from sparkpost import SparkPost
sp = SparkPost()
sp.templates.get('my-template-id')
List all templates
----------------------

.. code-block:: python
from sparkpost import SparkPost
sp = SparkPost()
sp.templates.list()
API reference
-------------

:doc:`/api/templates`


Further examples
----------------

See the `python-sparkpost templates examples`_.

.. _python-sparkpost templates examples: https://github.com/SparkPost/python-sparkpost/tree/master/examples/templates


Additional documentation
------------------------

See the `SparkPost Templates API Reference`_.

.. _SparkPost Templates API Reference: https://www.sparkpost.com/api#/reference/templates
11 changes: 11 additions & 0 deletions examples/templates/create_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from sparkpost import SparkPost

sp = SparkPost('YOUR API KEY')
response = sp.templates.create(
id='TEST_ID',
name='Test Template',
from_email='test@test.com',
subject='Test email template!',
html='<b>This is a test email template!</b>'
)
print response
5 changes: 5 additions & 0 deletions examples/templates/delete_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from sparkpost import SparkPost

sp = SparkPost('YOUR API KEY')
template = sp.transmission.delete('template_id')
print template
5 changes: 5 additions & 0 deletions examples/templates/get_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from sparkpost import SparkPost

sp = SparkPost('YOUR API KEY')
template = sp.transmission.get('template_id')
print template
5 changes: 5 additions & 0 deletions examples/templates/list_templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from sparkpost import SparkPost

sp = SparkPost('YOUR API KEY')
template_list = sp.templates.list()
print template_list
9 changes: 9 additions & 0 deletions examples/templates/preview_draft_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from sparkpost import SparkPost

sp = SparkPost('YOUR API KEY')
sub_data = {
'first_name': 'John',
'last_name': 'Doe'
}
template = sp.transmission.preview('template_id', sub_data, True)
print template
9 changes: 9 additions & 0 deletions examples/templates/preview_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from sparkpost import SparkPost

sp = SparkPost('YOUR API KEY')
sub_data = {
'first_name': 'John',
'last_name': 'Doe'
}
template = sp.transmission.preview('template_id', sub_data)
print template
11 changes: 11 additions & 0 deletions examples/templates/update_template.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from sparkpost import SparkPost

sp = SparkPost('YOUR API KEY')
response = sp.templates.update(
'TEST_ID',
name='Test Template',
from_email='test@test.com',
subject='Updated Test email template!',
html='<b>This is a test email template! Updated!</b>'
)
print response
2 changes: 2 additions & 0 deletions sparkpost/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from .exceptions import SparkPostException
from .metrics import Metrics
from .templates import Templates
from .transmissions import Transmissions


Expand All @@ -26,6 +27,7 @@ def __init__(self, api_key=None, base_uri='https://api.sparkpost.com',
self.api_key = api_key

self.metrics = Metrics(self.base_uri, self.api_key)
self.templates = Templates(self.base_uri, self.api_key)
self.transmissions = Transmissions(self.base_uri, self.api_key)
# Keeping self.transmission for backwards compatibility.
# Will be removed in a future release.
Expand Down
182 changes: 182 additions & 0 deletions sparkpost/templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import json

from .base import Resource


class Templates(Resource):
"""
Templates class used to create, update, delete, list and get templates. For
detailed request and response formats, see the `Templates API documentation
<https://www.sparkpost.com/api#/reference/templates>`_.
"""

key = 'templates'

def _translate_keys(self, **kwargs):
model = {
'content': {},
'options': {}
}

if 'id' in kwargs:
model['id'] = kwargs.get('id')
model['name'] = kwargs.get('name')
model['description'] = kwargs.get('description')
model['published'] = kwargs.get('published')

model['options']['open_tracking'] = kwargs.get('track_opens')
model['options']['click_tracking'] = kwargs.get('track_clicks')
model['options']['transactional'] = kwargs.get('is_transactional')

model['content']['html'] = kwargs.get('html')
model['content']['text'] = kwargs.get('text')
model['content']['subject'] = kwargs.get('subject')
model['content']['from'] = kwargs.get('from_email')
model['content']['reply_to'] = kwargs.get('reply_to')
model['content']['headers'] = kwargs.get('custom_headers')

return model

def create(self, **kwargs):
"""
Create a template based on the supplied parameters
:param str id: ID used to reference the template
:param str name: Editable display name
:param str description: Detailed description of the template
:param bool published: Defaults to False. Whether the template is a
published or draft version
:param bool track_opens: Defaults to transmission level setting.
Used to track opens of transmission
:param bool track_clicks: Defaults to transmission level setting.
Used to track clicks of transmission
:param bool is_transactional: Defaults to transmission level setting.
Distinguishes between transactional and non-transactional messages
for unsubscribe and suppression purposes
:param str html: HTML part of template
:param str text: Text part of template
:param str subject: Subject of template
:param str from_email: Friendly from of template, domain must be a
verified sending domain to your account or template create
will fail
:param str reply_to: Reply to of template
:param dict custom_headers: Used to set any headers associated with
template
:returns: a ``dict`` with the ID
:raises: :exc:`SparkPostAPIException` if template uses an unverified
sending domain or there's a syntax error in the content
"""
payload = self._translate_keys(**kwargs)
results = self.request('POST', self.uri, data=json.dumps(payload))
return results

def update(self, template_id, **kwargs):
"""
Update a template by ID based on the supplied parameters
:param str template_id: ID of the template you want to retrieve
:param str name: Editable display name
:param str description: Detailed description of the template
:param bool published: Defaults to False. Whether the template is a
published or draft version
:param bool track_opens: Defaults to transmission level setting.
Used to track opens of transmission
:param bool track_clicks: Defaults to transmission level setting.
Used to track clicks of transmission
:param bool is_transactional: Defaults to transmission level setting.
Distinguishes between transactional and non-transactional messages
for unsubscribe and suppression purposes
:param str html: HTML part of template
:param str text: Text part of template
:param str subject: Subject of template
:param str from_email: Friendly from of template, domain must be a
verified sending domain to your account or template create
will fail
:param str reply_to: Reply to of template
:param dict custom_headers: Used to set any headers associated with
template
:returns: TODO
:raises: :exc:`SparkPostAPIException` if template is not found
"""
uri = "%s/%s" % (self.uri, template_id)
payload = self._translate_keys(**kwargs)
results = self.request('PUT', uri, data=json.dumps(payload))
return results

def delete(self, template_id):
"""
Delete a template by ID
:param str template_id: ID of the template you want to delete
:returns: TODO
:raises: :exc:`SparkPostAPIException` if template is not found or if
template is in use
"""
uri = "%s/%s" % (self.uri, template_id)
results = self.request('DELETE', uri)
return results

def get(self, template_id, draft=None):
"""
Get a template by ID
:param str template_id: ID of the template you want to retrieve
:param bool draft: Defaults to None. If True, returns the most
recent draft template. If False, returns the most recent published
template. If None, returns the most recent template version
regardless of draft or published.
:returns: the requested template if found
:raises: :exc:`SparkPostAPIException` if template is not found
"""
uri = "%s/%s" % (self.uri, template_id)
params = {}
if draft is not None:
params['draft'] = str(draft).lower()
results = self.request('GET', uri, params=params)
return results

def list(self):
"""
Get a list of your templates
:returns: list of templates
:raises: :exc:`SparkPostAPIException` if API call fails
"""
results = self.request('GET', self.uri)
return results

def preview(self, template_id, substitution_data, draft=None):
"""
Get a preivew of your template by ID with the
provided substitution_data
:param str template_id: ID of the template you want to retrieve
:param dict substitution_data: data to be substituted in the
template content
:param bool draft: Defaults to None. If True, previews the most
recent draft template. If False, previews the most recent published
template. If None, previews the most recent template version
regardless of draft or published.
:returns: the requested template if found with content expanded using
substitution data provided
:raises: :exc:`SparkPostAPIException` if API call fails
"""
uri = "%s/%s/preview" % (self.uri, template_id)
params = {}
if draft is not None:
params['draft'] = str(draft).lower()
results = self.request('POST',
uri,
params=params,
data=json.dumps(substitution_data))
return results

0 comments on commit 4f37988

Please sign in to comment.