【问题标题】:TypeError: cannot use a string pattern on a bytes-like object -- mimetypes.guess_typeTypeError:不能在类似字节的对象上使用字符串模式——mimetypes.guess_type
【发布时间】:2020-12-10 22:35:47
【问题描述】:

我正在尝试使用 pathfs 检测存储在 mongodb 数据库中的文件的 mimetype。我正在使用“mimetypes”来执行此操作,我尝试将文件作为字节传递,但收到错误 TypeError: cannot use a string pattern on a bytes-like object

我的代码:

location = cur_post['file']
file_mimetype = mimetypes.guess_type(fs.get(location).read())
print(file_mimetype)
return send_file(BytesIO(fs.get(location).read()), mimetype=file_mimetype, as_attachment=False, attachment_filename=(str(random.randint(10000000,99999999)) + '.pdf'))

我也试过mimetypes.guess_type(io.BytesIO(fs.get(location).read())),也遇到了类似的错误

【问题讨论】:

  • mimetypes 使用文件名从文件扩展名中猜测 mime 类型,而不是通过从文件内容中读取魔术字节。使用不同的库,例如 python-magic

标签: python mime-types


【解决方案1】:

在不了解更多有关底层代码和您正在使用的资产的情况下,我只能做出有根据的猜测,您可能需要将字节对象解码为字符串。

类似的东西:

 file_mimetype = mimetypes.guess_type(fs.get(location).read().decode())

但正如已经提到的,您可能没有适合这项工作的工具。对于文件识别,我通常看到filetype 库比其他任何东西都更常用。

import filetype

with open('grail.png', 'rb') as fh: grail = fh.read()
type(grail) # bytes
best_guess = filetype.guess(grail)
print(best_guess.mime)  # 'image/png'

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 2016-06-03
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多