Skip to content

Commit

Permalink
Add support for decimal
Browse files Browse the repository at this point in the history
  • Loading branch information
Sébastien RAMAGE committed Oct 6, 2020
1 parent fb733ac commit 58cfb81
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion rpc4django/version.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
_MAJOR = 0
_MINOR = 6
_PATCH = 3
_PATCH = 4

__version__ = str(_MAJOR) + '.' + str(_MINOR) + '.' + str(_PATCH)

Expand Down
13 changes: 13 additions & 0 deletions rpc4django/xmlrpcdispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from defusedxml import xmlrpc
from django.conf import settings
from collections import OrderedDict
from decimal import Decimal

if sys.version_info.major == 2:
# Python2
Expand All @@ -22,6 +23,7 @@
Marshaller.dispatch[OrderedDict] = Marshaller.dump_struct



# Transparently support datetime.date as datetime.datetime
def dump_date(instance, value, write):
value = datetime.datetime.combine(value, datetime.time.min)
Expand All @@ -30,6 +32,17 @@ def dump_date(instance, value, write):

Marshaller.dispatch[datetime.date] = dump_date


# Add support for decimal
def dump_decimal(instance, value, write):
value = float(value)
write("<value><bigdecimal>")
write(str(value))
write("</bigdecimal></value>\n")


Marshaller.dispatch[Decimal] = dump_decimal

try:
# django 1.11 compat
from django.utils.deprecation import CallableBool
Expand Down
12 changes: 12 additions & 0 deletions tests/test_xmlrpcdispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import unittest
from django.core.exceptions import ImproperlyConfigured
from decimal import Decimal


try:
Expand All @@ -25,6 +26,9 @@
class TestXMLRPCDispatcher(unittest.TestCase):

def setUp(self):
def echotest(a):
return a

def kwargstest(a, b, **kwargs):
if kwargs.get('c', None) is not None:
return True
Expand All @@ -37,6 +41,7 @@ def requestargtest(request,a):
return request

self.dispatcher = XMLRPCDispatcher()
self.dispatcher.register_function(echotest, 'echotest')
self.dispatcher.register_function(kwargstest, 'kwargstest')
self.dispatcher.register_function(requestargtest, 'requestargtest')
self.dispatcher.register_function(withoutargstest, 'withoutargstest')
Expand Down Expand Up @@ -89,6 +94,13 @@ def test_billion_laughs(self):
ret = self.dispatcher.dispatch(payload)
self.assertRaises(Fault, loads, ret)

def test_decimal(self):
d = Decimal('1.23456')
xml = dumps((d,), 'echotest')
ret = self.dispatcher.dispatch(xml)
out, name = loads(ret)
self.assertEqual(d, out[0])
self.assertTrue(isinstance(out[0], Decimal))


if __name__ == '__main__':
Expand Down

0 comments on commit 58cfb81

Please sign in to comment.