简体   繁体   English

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

[英]How to return a float (or int) with a sanic API?

I am creating a simple Sanic REST API but cannot figure out how return numeric data. 我正在创建一个简单的Sanic REST API,但无法弄清楚如何返回数字数据。 After looking at the docs , it appears that you can only return json , html , text , etc., but no float or int . 查看文档后 ,您似乎只能返回jsonhtmltext等,但不能返回floatint

I am following the basic example in the docs, except have switched the return to a float: 我将遵循文档中的基本示例,但将返回值切换为浮点数:

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)

However, it works perfectly if the return statement is return json({"hello": "world"}) . 但是,如果return语句是return json({"hello": "world"}) ,则它可以完美地工作。 Why can I not return a float? 为什么我不能退还浮存金? I can return it as return text(1.1) , but then does the client who calls it receive it as a str (as opposed to a float )? 我可以将其作为return text(1.1) ,但是调用它的客户端是否将它作为str接收(而不是float )?

Just JSON your number. 只需JSON您的电话号码即可。

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

With Sanic: 使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM