Search code examples
python-3.xsanic

How to respond to a boolean type in sanic?


I need to respond directly to True or False. How can I do this? Json, text, raw.... can't code

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

Error

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'

Append:

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)

I just want to simply return True or False.


Solution

  • I think what you are looking for is something like this:

    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)
    

    You just need to wrap your response in response.json.

    These endpoints should work as expected:

    $ 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
    

    And

    $ 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