如何使用sanic API返回浮点数(或整数)?

时间:2019-01-27 01:11:55

标签: python python-3.x sanic

我正在创建一个简单的Sanic REST API,但无法弄清楚如何返回数字数据。查看at the docs后,您似乎只能返回jsonhtmltext等,但不能返回floatint

我遵循文档中的基本示例,但已将返回值切换为浮点数:

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route("/")
async def test(request):
    return 1.1

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

但是,如果return语句为return json({"hello": "world"}),则可以很好地工作。为什么我不能退还浮存金?我可以将其返回为return text(1.1),但是调用它的客户端是否会将它作为str(而不是float)来接收?

1 个答案:

答案 0 :(得分:1)

只需使用JSON即可输入您的电话号码。

>>> import json
>>> s = json.dumps(543.34)
>>> s
'543.34'
>>> json.loads(s)
543.34

与Sanic:

from sanic import Sanic, response
from sanic.response import json

app = Sanic()

@app.route("/")
async def test(request):
    return response.json(1.1)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)