如何使用sanic API返回float(或int)?

2024-10-03 06:32:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的sanicrestapi,但是我不知道如何返回数字数据。在查看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相反)?你知道吗


Tags: the数据textfromimportjsonappdocs
1条回答
网友
1楼 · 发布于 2024-10-03 06:32:11

只要你的号码。你知道吗

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

与三一重工:

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)

相关问题 更多 >