Skip to content

Commit

Permalink
Add support for api keys
Browse files Browse the repository at this point in the history
  • Loading branch information
eddiezane committed Apr 27, 2015
1 parent 312fb7b commit 138c998
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 13 deletions.
14 changes: 9 additions & 5 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
v1.3.0 (2014-01-23)
===================
# Change Log
All notable changes to this project will be documented in this file.

* Add new method for ASM Group ID via [#98](https://github.com/sendgrid/sendgrid-python/pull/98)
* Add CHANGELOG.md
## [1.4.0] - Unreleased
### Added
- Support for API keys

--
## [1.3.0] - 2014-01-23
### Added
- Add new method for ASM Group ID via [#98](https://github.com/sendgrid/sendgrid-python/pull/98)
- Add CHANGELOG.md
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ encouraged to set ``raise_errors`` to ``True`` for forwards compatibility.

``SendGridError`` is a base-class for all SendGrid-related exceptions.

Usage
~~~~~

To begin using this library create a new instance of `SendGridClient` with your SendGrid credentials or a SendGrid API Key. API Key is the preferred method. API Keys are in beta. To configure API keys, visit https://sendgrid.com/beta/settings/api_key.

.. code:: python
sg = sendgrid.SendGridClient('sendgrid_username', 'sendgrid_password')
# or
sg = sendgrid.SendGridClient('sendgrid_apikey')
Methods
~~~~~~~

Expand Down
28 changes: 23 additions & 5 deletions sendgrid/sendgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class SendGridClient(object):

"""SendGrid API."""

def __init__(self, username, password, **opts):
def __init__(self, username_or_apikey, password=None, **opts):

This comment has been minimized.

Copy link
@wowzer

wowzer Jun 9, 2015

This is a breaking API change. Can you please introduce a separate parameter for api key. Just to be clear, I was explicitly entering the parameter name for "username" and this change breaks the API:
sendgrid.SendGridClient(username=SENDGRID_USERNAME, password=SENDGRID_PASSWORD)

"""
Construct SendGrid API object.
Expand All @@ -31,8 +31,17 @@ def __init__(self, username, password, **opts):
1.0.0, the default will be changed to True, so you are
recommended to pass True for forwards compatability.
"""
self.username = username
self.password = password

# Check if username + password or api key
if password is None:
# API Key
self.username = None
self.password = username_or_apikey
else:
# Username + password
self.username = username_or_apikey
self.password = password

self.useragent = 'sendgrid/' + __version__ + ';python'
self.host = opts.get('host', 'https://api.sendgrid.com')
self.port = str(opts.get('port', '443'))
Expand All @@ -52,8 +61,6 @@ def _build_body(self, message):
setattr(message, k, v.encode('utf-8'))

values = {
'api_user': self.username,
'api_key': self.password,
'to[]': message.to if message.to else [message.from_email],
'toname[]': message.to_name,
'cc[]': message.cc,
Expand All @@ -68,6 +75,12 @@ def _build_body(self, message):
'date': message.date,
'x-smtpapi': message.json_string()
}

if self.username != None:
# Using username + password
values['api_user'] = self.username
values['api_key'] = self.password

for k in list(values.keys()):
if not values[k]:
del values[k]
Expand All @@ -87,6 +100,11 @@ def _make_request(self, message):
data = urlencode(self._build_body(message), True).encode('utf-8')
req = urllib_request.Request(self.mail_url, data)
req.add_header('User-Agent', self.useragent)

if self.username is None:
# Using API key
req.add_header('Authorization', 'Bearer ' + self.password)

response = urllib_request.urlopen(req, timeout=10)
body = response.read()
return response.getcode(), body
Expand Down
10 changes: 7 additions & 3 deletions test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,18 @@
from sendgrid.exceptions import SendGridClientError, SendGridServerError
from sendgrid.sendgrid import HTTPError


SG_USER, SG_PWD = os.getenv('SG_USER'), os.getenv('SG_PWD')

SG_USER = os.getenv('SG_USER') or 'SENDGRID_USERNAME'
SG_PWD = os.getenv('SG_PWD') or 'SENDGRID_PASSWORD'

class TestSendGrid(unittest.TestCase):
def setUp(self):
self.sg = SendGridClient(SG_USER, SG_PWD)

def test_apikey_init(self):
sg = SendGridClient(SG_PWD)
self.assertEqual(sg.password, SG_PWD)
self.assertIsNone(sg.username)

@unittest.skipUnless(sys.version_info < (3, 0), 'only for python2')
def test_unicode_recipients(self):
recipients = [unicode('[email protected]'), unicode('[email protected]')]
Expand Down

0 comments on commit 138c998

Please sign in to comment.