为由 urlopen() 或 requests.get() 创建的类文件对象提供文件名 [英] supply a filename for a file-like object created by urlopen() or requests.get()
问题描述
我正在使用 Telepot 库构建 Telegram 机器人.要发送从 Internet 下载的图片,我必须使用 sendPhoto 方法,它接受一个类似文件的对象.
浏览文档我发现了这个建议:
<块引用>如果类似文件的对象是通过 urlopen()
获取的,您很可能必须提供文件名,因为 Telegram 服务器需要知道文件扩展名.
所以问题是,如果我通过用 requests.get
打开它并像这样用 BytesIO
包装来获取我的类文件对象:
res = requests.get(some_url)tbot.sendPhoto(信使_id,io.BytesIO(res.content))
如何以及在何处提供文件名?
您可以提供文件名作为对象的 .name
属性.
使用 open()
打开文件有一个 .name 属性.
打开网址的地方没有.这就是文档特别提到这一点的原因.
<预><代码>>>>导入 urllib>>>url_file = urllib.open("http://example.com/index.html")>>>网址文件<addinfourl at 44 which fp = <open file 'nul', mode 'rb' at ADDRESS>>>>>url_file.nameAttributeError: addinfourl 实例没有属性名称"在你的情况下,你需要创建类似文件的对象,并给它一个 .name
属性:
res = requests.get(some_url)the_file = io.BytesIO(res.content)the_file.name = 'file.image'tbot.sendPhoto(信使_id,文件)
I am building a Telegram bot using a Telepot library. To send a picture downloaded from Internet I have to use sendPhoto method, which accepts a file-like object.
Looking through the docs I found this advice:
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.
So the question is, if I get my filelike object by opening it with requests.get
and wrapping with BytesIO
like so:
res = requests.get(some_url)
tbot.sendPhoto(
messenger_id,
io.BytesIO(res.content)
)
how and where do I supply a filename?
You would supply the filename as the object's .name
attribute.
Opening a file with open()
has a .name attribute.
>>> local_file = open("file.txt")
>>> local_file
<open file 'file.txt', mode 'r' at ADDRESS>
>>> local_file.name
'file.txt'
Where opening a url does not. Which is why the documentation specifically mentions this.
>>> 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'
In your case, you would need to create the file-like object, and give it a .name
attribute:
res = requests.get(some_url)
the_file = io.BytesIO(res.content)
the_file.name = 'file.image'
tbot.sendPhoto(
messenger_id,
the_file
)
这篇关于为由 urlopen() 或 requests.get() 创建的类文件对象提供文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!