为由 urlopen() 或 requests.get() 创建的类文件对象提供文件名



我正在使用Telepot库构建一个Telegram机器人。要发送从互联网下载的图片,我必须使用sendPhoto方法,该方法接受类似文件的对象。

浏览文档,我发现了以下建议:

如果类似文件的对象是由urlopen()获得的,您很可能必须提供一个文件名,因为 Telegram 服务器需要知道文件扩展名。

所以问题是,如果我通过用requests.get打开它并用BytesIO换行来获得我的文件状对象,如下所示:

res = requests.get(some_url)
tbot.sendPhoto(
messenger_id,
io.BytesIO(res.content)
)

如何以及在何处提供文件名?

您将提供文件名作为对象的.name属性。

使用open()打开文件具有 .name 属性。

>>> local_file = open("file.txt")
>>> local_file
<open file 'file.txt', mode 'r' at ADDRESS>
>>> local_file.name
'file.txt'

打开网址的地方没有。这就是为什么文档特别提到这一点的原因。

>>> import urllib
>>> url_file = urllib.open("http://example.com/index.html")
>>> url_file
<addinfourl at 44 whose fp = <open file 'nul', mode 'rb' at ADDRESS>>
>>> url_file.name
AttributeError: addinfourl instance has no attribute 'name'

在您的情况下,您需要创建类似文件的对象,并为其指定.name属性:

res = requests.get(some_url)
the_file = io.BytesIO(res.content)
the_file.name = 'file.image'
tbot.sendPhoto(
messenger_id,
the_file
)

相关内容

最新更新