Python I/O:如何使用来自io模块的wsgi.input流
在WSGI应用程序中,我们可以从WSGI.input字段读取行输入数据: 但是,我想使用新的io模块包装类似文件的对象: 问题是,Python I/O:如何使用来自io模块的wsgi.input流,python,io,wsgi,Python,Io,Wsgi,在WSGI应用程序中,我们可以从WSGI.input字段读取行输入数据: 但是,我想使用新的io模块包装类似文件的对象: 问题是,io.open不接受此类文件对象。你知道怎么做吗?我需要从env['wsgi.input']读取缓冲区。函数不接受file object作为第一个参数 但是,它接受表示打开文件句柄的整数。因此,您可以通过以下方式获得一些成功: f = io.open(env['wsgi.input'].fileno, 'rb') 附录: io模块是为Python3编写的,其中字符串
io.open
不接受此类文件对象。你知道怎么做吗?我需要从env['wsgi.input']
读取缓冲区。函数不接受file object作为第一个参数
但是,它接受表示打开文件句柄的整数。因此,您可以通过以下方式获得一些成功:
f = io.open(env['wsgi.input'].fileno, 'rb')
附录:
io模块是为Python3编写的,其中字符串处理与Python2有很大不同。在二进制模式下打开的文件上调用read()
在python 3中返回一个bytes
对象,但在python 2中返回一个str
,但是当使用io
模块和二进制模式包装文件时,io模块期望read()
返回字节
您可以尝试通过使原始文件对象返回字节来修复它:
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')
上面的函数包装了read()
方法,但可以完成包装readline()
。另外,包装readlines()
..还需要做一些额外的工作,现在它接受了文件,但它说:TypeError:read()应该返回bytes.ooops,fileno
是一个函数,而不是一个属性。我忘记真正调用函数了。代码现在已修复…它基本上意味着wsgi文件上的read()可能返回字符而不是字节。从模式字符串中删除“b”:在二进制模式下使用io模块,文件应该返回字节
,但文件的标准python 2实现返回astr
(这是io
模块的unicode
对象)访问wsgi.input上的fileno这样的输入超出了wsgi规范,如果希望应用程序符合wsgi,就不应该这样做。
f = io.open(env['wsgi.input'].fileno, 'rb')
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')