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

supply a filename for a file-like object created by urlopen() or requests.get()

我正在使用 Telepot library. To send a picture downloaded from Internet I have to use sendPhoto 方法构建 Telegram 机器人,该方法接受类似文件的对象。

通过查看文档我发现了这个建议:

If the file-like object is obtained by urlopen(), you most likely have to supply a filename because Telegram servers require to know the file extension.

所以问题是,如果我通过用 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'

打开 url 没有。这就是文档特别提到这一点的原因。

>>> 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
)