Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for serializing decimals #187

Merged
merged 1 commit into from
Dec 13, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 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,15 @@
ServerCls = Callable[..., 'HTTPServer']


def handle_decimals(obj):
# type: (Any) -> Any
# 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 +144,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