Sanic: How to respond to a boolean type?

Created on 28 Jul 2018  路  3Comments  路  Source: sanic-org/sanic

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

` 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'

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

`

question

Most helpful comment

Well, responding with a boolean has a lot of meanings.

  • I would recommend better in HTTP Status codes, I'd say that the statuses cover most of the use cases.
  • For cases where a body has to be returned, use the following:

    • json Content-Type, as @mikekeda said.

    • use response.text and return 0 or 1 or true or false??

    • If you need raw output, have you considered response.raw?

At the end of the day, boolean is a bit... and a (decimal or string) representation is what you see. If you really want to send a 1 bit, then I think you're better off with another internet protocol??

import ujson

from sanic import response

@bp.route('/data', methods=['GET'])
async def some_call(request):
    value = True
    return response.text(f'{value}')

    # or
    return response.text(ujson.dumps(value))

    # or using json
    return response.json(value)

    # using raw (HTTP is text based) so...
    # but this wont have encoding...
    return response.raw(f'{value}')

https://sanic.readthedocs.io/en/latest/sanic/response.html

All 3 comments

@EdwardBetts @cbess @kolanos @dkruchinin @joar

return json(True)

Well, responding with a boolean has a lot of meanings.

  • I would recommend better in HTTP Status codes, I'd say that the statuses cover most of the use cases.
  • For cases where a body has to be returned, use the following:

    • json Content-Type, as @mikekeda said.

    • use response.text and return 0 or 1 or true or false??

    • If you need raw output, have you considered response.raw?

At the end of the day, boolean is a bit... and a (decimal or string) representation is what you see. If you really want to send a 1 bit, then I think you're better off with another internet protocol??

import ujson

from sanic import response

@bp.route('/data', methods=['GET'])
async def some_call(request):
    value = True
    return response.text(f'{value}')

    # or
    return response.text(ujson.dumps(value))

    # or using json
    return response.json(value)

    # using raw (HTTP is text based) so...
    # but this wont have encoding...
    return response.raw(f'{value}')

https://sanic.readthedocs.io/en/latest/sanic/response.html

Was this page helpful?
0 / 5 - 0 ratings