【问题标题】:TypeError: coercing to Unicode: need string or buffer, _io.BytesIO foundTypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 _io.BytesIO
【发布时间】:2018-04-19 09:10:36
【问题描述】:

我正在尝试一周如何从烧瓶 POST 选项中将输入文件提供给 Textract。

@app.route('/input', methods=['POST'])
def input():
    request_file = request.files.get('file')
    r = textract.process(io.BytesIO(request_file.read()))
    return r 

上面的代码给我报错

TypeError:强制转换为 Unicode:需要字符串或缓冲区,_io.BytesIO 找到了

我用send_file 做了一个小测试来检查它是否真的需要输入,并检查 BytesIO 在我的情况下是否工作良好:

@app.route('/input', methods=['POST'])
def input():
    request_file = request.files.get('file')
    return send_file(io.BytesIO(request_file.read()),attachment_filename=
request_file.filename)

以上代码适用于 pdf 文件并发送响应(下载 pdf 文件)。当我尝试 .docx,.txt 文件时,它会在屏幕上显示一些奇怪的输出:PK

我的问题,我现在如何将此io.bytes(request_file.read()) 作为文件发送到 Textract?我试图到处寻找答案,但我找不到。

我现在应该解码还是编码?

【问题讨论】:

  • r = textract.process(io.BytesIO(request_file.read()).read())?
  • 不工作。抛出错误:TypeError: stat() 参数 1 必须是没有空字节的编码字符串,而不是 str

标签: python flask text-extraction bytesio


【解决方案1】:

textract.process() 需要一个字符串,但您发送的是 io.BytesIO(request_file.read())。我不确定你为什么使用io.BytesIO。你可以试试:

textract.process(request_file.read())

【讨论】:

  • 它给出错误:TypeError: stat() 参数 1 必须是没有空字节的编码字符串,而不是 str 。此 read() 正在读取内容而不是将文件发送到 textract
  • 我通过使用 os.path.join(app.config['UPLOAD_FOLDER'], filename) 将输入文件保存到磁盘来使其工作。但是 request_file.read() 对我不起作用(我想在不将其保存在磁盘上的情况下工作:/)
猜你喜欢
  • 2021-03-28
  • 2015-02-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 2011-05-13
相关资源
最近更新 更多