[Web-SIG] PEP 444 (aka Web3)

Masklinn masklinn at masklinn.net
Thu Sep 16 08:37:49 CEST 2010


> I generally like it.
> 
> About the *.file_wrapper removal, i suggest
> a PSGI-like approach where 'body' can contains a File Object.
> 
> def file_app(environ):
>    fd = open('/tmp/pippo.txt', 'r')
>    status = b'200 OK'
>    headers = [(b'Content-type', b'text/plain')]
>    body = fd
>    return body, status, headers
> 
As far as I understand it, `body` is an iterable so there should not be any problem with sending a file through directly in this manner. Better, the web3 spec specifically mandates that if the `body` iterable has a `close` method it must be called on request completion (second-to-last paragraph in the specification details section [0]). So a File Object as a body is already completely handled by web3.

On the other hand, `body` has to yield bytes, so `fd = open('/tmp/pippo.txt', 'rb')` I think.

> def file_app(environ):
>    fd = open('/tmp/pippo.txt', 'r')
>    status = b'200 OK'
>    headers = [(b'Content-type', b'text/plain')]
>    body = [b'Header', fd, b'Footer']
>    return body, status, headers
> 
> 
> (and what about returning multiple File objects ?)
> 
Well you could just use `itertools.chain([b'Header'], fd, [b'Footer'])` and `itertools.chain(*files)` respectively though there is the issue that, with non-refcounting GCs (Jython, IronPython, pypy), these may stay unclosed for quite some time. A good idea would probably be some kind of `closingchain` replacement to `itertools.chain` which would be able to `close()` its sub-iterables if they're closable (or maybe a `contextchain` which calls `__enter__` and `__exit__` on its sub-iterables if those are available).

[0] http://python.org/dev/peps/pep-0444/#specification-details


More information about the Web-SIG mailing list