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

时间:2017-03-15 12:12:23

标签: python python-requests telegram

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

通过文档查看我的建议:

  

如果urlopen()获取了类文件对象,则很可能必须提供文件名,因为Telegram服务器需要知道文件扩展名。

所以问题是,如果我通过使用requests.get打开它并使用BytesIO包装来获取我的文件类对象:

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

我如何以及在哪里提供文件名?

1 个答案:

答案 0 :(得分:5)

您将提供文件名作为对象的.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.hmtl")
>>>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
)