Fun with IO

Chris Angelico rosuav at gmail.com
Fri Jan 17 14:16:04 EST 2020


On Sat, Jan 18, 2020 at 6:09 AM Frank Millman <frank at chagford.com> wrote:
> So I
> tried passing the client_writer directly to the handler -
>
>      await pdf_handler(client_writer)
>      client_writer.write(b'\r\n')
>
> It works! ReportLab accepts client_writer as a file-like object, and
> writes to it directly. I cannot use chunking, so I just let it do its thing.
>
> Can anyone see any problem with this?
>

Looks good to me! The only potential problem would be if the
pdf_handler needs a seekable file-like object (eg if it needs to write
a header that contains the size of the entire file), but it appears to
work, so you're almost certainly safe.

In more general terms, what you've done is basically write directly to
the socket, rather than writing to a mythical file and storing it in
memory, then dumping that memory out to the socket. Which (as long as
you don't need to seek or edit) is absolutely an acceptable way to do
things, and is likely to give better performance.

ChrisA


More information about the Python-list mailing list