1

我需要直接回应 True 或 False。我怎样才能做到这一点?Json, text, raw....不能编码

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。

4

1 回答 1

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
于 2018-07-29T06:00:56.743 回答