Skip to content

Commit c49088e

Browse files
committed
Fix fields.Float to output actual floats per JSON spec
1 parent 43585b6 commit c49088e

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

flask_restful/fields.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ class Float(Raw):
246246

247247
def format(self, value):
248248
try:
249-
return repr(float(value))
249+
return float(value)
250250
except ValueError as ve:
251251
raise MarshallingException(ve)
252252

tests/test_api.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,5 +767,21 @@ def get(self):
767767
self.assertEquals(resp.status_code, 302)
768768
self.assertEquals(resp.headers['Location'], 'http://localhost/')
769769

770+
def test_json_float_marshalled(self):
771+
app = Flask(__name__)
772+
api = flask_restful.Api(app)
773+
774+
class FooResource(flask_restful.Resource):
775+
fields = {'foo': flask_restful.fields.Float}
776+
def get(self):
777+
return flask_restful.marshal({"foo": 3.0}, self.fields)
778+
779+
api.add_resource(FooResource, '/api')
780+
781+
app = app.test_client()
782+
resp = app.get('/api')
783+
self.assertEquals(resp.status_code, 200)
784+
self.assertEquals(resp.data, '{"foo": 3.0}')
785+
770786
if __name__ == '__main__':
771787
unittest.main()

tests/test_fields.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@ def check_field(expected, field, value):
2222

2323
def test_float():
2424
values = [
25-
("-3.13", "-3.13"),
26-
(str(-3.13), "-3.13"),
27-
(3, "3"),
25+
("-3.13", -3.13),
26+
(str(-3.13), -3.13),
27+
(3, 3.0),
2828
]
2929
for value, expected in values:
30-
yield check_field, expected, fields.Arbitrary(), value
30+
yield check_field, expected, fields.Float(), value
3131

3232

3333
def test_boolean():
@@ -193,7 +193,7 @@ def test_int_decode_error(self):
193193

194194
def test_float(self):
195195
field = fields.Float()
196-
self.assertEquals('3.0', field.output("hey", {'hey': 3.0}))
196+
self.assertEquals(3.0, field.output("hey", {'hey': 3.0}))
197197

198198
def test_float_decode_error(self):
199199
field = fields.Float()

0 commit comments

Comments
 (0)