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

发布于 2021-01-29 16:07:32

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

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

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

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

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

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

关注者
0
被浏览
80
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看