Sanic: response.file_stream of StringIO not working

Created on 13 Jul 2018  路  5Comments  路  Source: sanic-org/sanic

Hi , first thank for all your work on SANIC

I want a return a BIG "file" which is in reality a StringIO

but I get TypeError: expected str, bytes or os.PathLike object, not _io.StringIO

@app.route('/test')
async def test(request):
    strIO = StringIO()
    strIO.write('Hello from Dan Jacob and Stephane Wirtel !')
    strIO.seek(0)
    return await response.file_stream(strIO)

am I doing an error or StringIO is not compatible with SANIC ?

thank you

Most helpful comment

For someone who came here after trying to return _io.BytesIO as a file response (i.e 1st argument to response.file) and getting an error saying - TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO.

Just use response.raw(_io.BytesIO, headers={}) and it'll work. (Setting headers is optional, obviously)

All 5 comments

Thank you , could I propose a PR for that pls ?

@raphaelauv - You should check out the sanic.response.stream function.

@app.route("/")`
async def test(request):

    output = io.StringIO()
    output.write('First, line.\n')
    output.write('First, line.\n')
    output.write('First, line.\n')
    output.seek(0)

    async def sample_streaming_fn(response):
        while True:
            rst = output.readline()
            if not rst:
                break
            else:
                response.write(rst)

    return stream(sample_streaming_fn, content_type='text/csv')

Yes it work , sorry for that boring question
Thank you !

For someone who came here after trying to return _io.BytesIO as a file response (i.e 1st argument to response.file) and getting an error saying - TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO.

Just use response.raw(_io.BytesIO, headers={}) and it'll work. (Setting headers is optional, obviously)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

geekpy picture geekpy  路  4Comments

graingert picture graingert  路  3Comments

fiecato picture fiecato  路  3Comments

ZeeRoc picture ZeeRoc  路  3Comments

mobdim picture mobdim  路  4Comments