如何响应sanic中的布尔类型?

时间:2018-07-28 08:50:02

标签: python-3.x sanic

我需要直接回答True或False。我怎样才能做到这一点? Json,文字,原始。。。 代码

if param == signature:
    return True
else:
    return False

错误

File "/usr/local/lib/python3.5/dist-packages/sanic/server.py", line 337, in 
write_response
response.output(
AttributeError: 'bool' object has no attribute 'output'

追加:

from sanic.response import json, text

@service_bp.route('/custom', methods=['GET'])
async def cutsom(request):
    signature = request.args['signature'][0]
    timestamp = request.args['timestamp'][0]
    nonce = request.args['nonce'][0]

    token = mpSetting['custom_token']
    param = [token, timestamp, nonce]
    param.sort()
    param = "".join(param).encode('utf-8')
    sha1 = hashlib.sha1()
    sha1.update(param)
    param = sha1.hexdigest()
    print(param, signature, param == signature)

    if param == signature:
        return json(True)
    else:
        return json(False)

我只想简单地返回True或False。

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是这样的东西:

from sanic import Sanic
from sanic.response import json

app = Sanic()


@app.route("/myroute")
async def myroute(request):
    param = request.raw_args.get('param', '')
    signature = 'signature'
    output = True if param == signature else False
    return json(output)

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

您只需要将响应包装在response.json中即可。

这些端点应该可以正常工作:

$ curl -i http://localhost:7777/myroute 

HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 5
Content-Type: application/json

false

$ curl -i http://localhost:7777/myroute\?param\=signature

HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 4
Content-Type: application/json

true