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

kur*_*tgn 9 python python-requests telegram

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

查看文档,我发现以下建议:

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

所以问题是,如果我通过打开文件requests.getBytesIO像这样包装来得到文件对象:

res = requests.get(some_url)
tbot.sendPhoto(
    messenger_id,
    io.BytesIO(res.content)
)
Run Code Online (Sandbox Code Playgroud)

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

alx*_*wrd 11

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

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

>>>local_file = open("file.txt")
>>>local_file
<open file 'file.txt', mode 'r' at ADDRESS>
>>>local_file.name
'file.txt'
Run Code Online (Sandbox Code Playgroud)

在没有打开URL的地方。这就是为什么文档专门提到了这一点。

>>>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'
Run Code Online (Sandbox Code Playgroud)

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

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

tbot.sendPhoto(
    messenger_id,
    the_file
)
Run Code Online (Sandbox Code Playgroud)