Skip to content

Commit b74cf12

Browse files
committed
Merge pull request flask-restful#219 from twilio/fix-float-field
Fix fields.Float to output actual floats per JSON spec
2 parents 4f0b18b + c49088e commit b74cf12

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
@@ -249,7 +249,7 @@ class Float(Raw):
249249

250250
def format(self, value):
251251
try:
252-
return repr(float(value))
252+
return float(value)
253253
except ValueError as ve:
254254
raise MarshallingException(ve)
255255

tests/test_api.py

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

755+
def test_json_float_marshalled(self):
756+
app = Flask(__name__)
757+
api = flask_restful.Api(app)
758+
759+
class FooResource(flask_restful.Resource):
760+
fields = {'foo': flask_restful.fields.Float}
761+
def get(self):
762+
return flask_restful.marshal({"foo": 3.0}, self.fields)
763+
764+
api.add_resource(FooResource, '/api')
765+
766+
app = app.test_client()
767+
resp = app.get('/api')
768+
self.assertEquals(resp.status_code, 200)
769+
self.assertEquals(resp.data, '{"foo": 3.0}')
770+
755771
if __name__ == '__main__':
756772
unittest.main()

tests/test_fields.py

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

2727
def test_float():
2828
values = [
29-
("-3.13", "-3.13"),
30-
(str(-3.13), "-3.13"),
31-
(3, "3"),
29+
("-3.13", -3.13),
30+
(str(-3.13), -3.13),
31+
(3, 3.0),
3232
]
3333
for value, expected in values:
34-
yield check_field, expected, fields.Arbitrary(), value
34+
yield check_field, expected, fields.Float(), value
3535

3636

3737
def test_boolean():
@@ -179,7 +179,7 @@ def test_int_decode_error(self):
179179

180180
def test_float(self):
181181
field = fields.Float()
182-
self.assertEquals('3.0', field.output("hey", {'hey': 3.0}))
182+
self.assertEquals(3.0, field.output("hey", {'hey': 3.0}))
183183

184184
def test_float_decode_error(self):
185185
field = fields.Float()

0 commit comments

Comments
 (0)