Python I/O: How to use the wsgi.input stream from io module
Question: In a WSGI application we can read the row input data from the _wsgi.input_
field:

    
    
    def application(env, start_response):
            .....
            data = env['wsgi.input'].read(num_bytes)
            .....
    

However, I want to wrap the file-like object using the new _io_ module:

    
    
    import io
    def application(env, start_response):
            .....
            f = io.open(env['wsgi.input'], 'rb')
            buffer = bytearray(buff_size)
            read = f.readinto(buffer)
            .....
    

The problem is that `io.open` doesn't accept these kind of file objects. Any
idea on how to do that? I need to read from `env['wsgi.input']` to a buffer.


Answer: the `io.open()` function does not accept file-object as the first parameter.

however, it accepts an integer representing the handle to an open file. so you
may have some success using:

    
    
    f = io.open(env['wsgi.input'].fileno(), 'rb')
    

**addendum:**

the io module is written for python 3, where string handling is quite
different from python 2. calling `read()` on a file opened in binary mode
returns a `bytes` object in python 3, but a `str` in python 2, but when
wrapping a file using the `io` module and using binary mode, the io module
expect `read()` to return `bytes`.

you can try fixing your original file object by making it return bytes():

    
    
    def fix(file):
        # wrap 'func' to convert its return value to bytes using the specified encoding
        def wrap(func, encoding):
            def read(*args, **kwargs):
                return bytes(func(*args, **kwargs), encoding)
            return read
        file.read = wrap(file.read, 'ascii')
    
    fix(env['wsgi.input'])
    f = io.open(env['wsgi.input'].fileno(), 'rb')
    

the above function wraps the `read()` method, but can be completed to wrap
`readline()`. also, a small additional work is required to wrap
`readlines()`...

