Skip to content

Commit

Permalink
Add support for serializing decimals
Browse files Browse the repository at this point in the history
Lambda supports serializing decimals to json,
so we need to support that as well in chalice local.
  • Loading branch information
jamesls committed Dec 1, 2016
1 parent afc3457 commit 118a104
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 10 additions & 1 deletion chalice/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""
import json
import decimal
import functools
from collections import namedtuple
from BaseHTTPServer import HTTPServer
Expand All @@ -22,6 +23,14 @@
ServerCls = Callable[..., 'HTTPServer']


def handle_decimals(obj):
# Lambda will automatically serialize decimals so we need
# to support that as well.
if isinstance(obj, decimal.Decimal):
return float(obj)
return obj


class RouteMatcher(object):
def __init__(self, route_urls):
# type: (List[str]) -> None
Expand Down Expand Up @@ -134,7 +143,7 @@ def _do_invoke_view_function(self, lambda_event):

def _send_http_response(self, lambda_event, response, status_code=200):
# type: (EventType, Any, int) -> None
json_response = json.dumps(response)
json_response = json.dumps(response, default=handle_decimals)
self.send_response(status_code)
self.send_header('Content-Length', str(len(json_response)))
self.send_header('Content-Type', 'application/json')
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/test_local.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from chalice import local, BadRequestError
import json
import decimal
import pytest
from pytest import fixture
from StringIO import StringIO
Expand Down Expand Up @@ -56,6 +57,10 @@ def patch():
def badrequest():
raise BadRequestError('bad-request')

@demo.route('/decimals')
def decimals():
return decimal.Decimal('100')

return demo


Expand Down Expand Up @@ -156,6 +161,11 @@ def test_can_support_patch_method(handler):
handler.do_PATCH()
assert _get_body_from_response_stream(handler) == {'patch': True}

def test_can_support_decimals(handler):
set_current_request(handler, method='GET', path='/decimals')
handler.do_PATCH()
assert _get_body_from_response_stream(handler) == 100


def test_unsupported_methods_raise_error(handler):
set_current_request(handler, method='POST', path='/index')
Expand Down

0 comments on commit 118a104

Please sign in to comment.