代码之家  ›  专栏  ›  技术社区  ›  John Doe.

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

  •  1
  • John Doe.  · 技术社区  · 7 年前

    我需要直接回应真假。我该怎么做?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)
    

    我只想简单地返回真或假。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Adam Hopkins    7 年前

    我想你要找的是这样的东西:

    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
    
    推荐文章