Sanic json response in streaming

How can I write json in response when streaming data:

async def docker(request):
    async def sample_streaming_fn(response):
        await response.write(json({"test": test}))
        await asyncio.sleep(1)
    return stream(sample_streaming_fn, content_type='text/event-stream') 

When iI try this i received aerror TypeError: %b requires a bytes-like object, or an object that implements __bytes__, not 'dict'

response.write() only accept bytes like object , So, dump the dict into json bytes should work:

from ujson import dumps

async def docker(request):
    async def sample_streaming_fn(response):
        await response.write(dumps({"test": test}))
        await asyncio.sleep(1)

    return stream(sample_streaming_fn, content_type='text/event-stream')
2 Likes

Yeah, @ZinkLu is right, you’re calling

json({"test": test}) and I believe you’re imported it from Sanic.response module, if yes json function returns HTTPResponse instance. that’s the reason why you’re getting the error.

For your case, you should use the dumps function, from json package.

1 Like