mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2025-02-16 18:31:45 +01:00
Download changed (#459)
* DownBytes added * File.downbyte changed * Changed file.download();Remove downbyte() * Fixed typo * add docstring, make custom_path and out mutually exclusive, rename downbytes to retrieve * remove trailing whitespace * run pre-commit hooks
This commit is contained in:
parent
a37add39f4
commit
c3984e1bf1
2 changed files with 35 additions and 9 deletions
|
@ -65,17 +65,35 @@ class File(TelegramObject):
|
|||
|
||||
return File(bot=bot, **data)
|
||||
|
||||
def download(self, custom_path=None):
|
||||
def download(self, custom_path=None, out=None):
|
||||
"""
|
||||
Args:
|
||||
custom_path (str):
|
||||
Download this file. By default, the file is saved in the current working directory with its
|
||||
original filename as reported by Telegram. If a ``custom_path`` is supplied, it will be
|
||||
saved to that path instead. If ``out`` is defined, the file contents will be saved to that
|
||||
object using the ``out.write`` method. ``custom_path`` and ``out`` are mutually exclusive.
|
||||
|
||||
Keyword Args:
|
||||
custom_path (Optional[str]): Custom path.
|
||||
out (Optional[object]): A file-like object. Must be opened in binary mode, if
|
||||
applicable.
|
||||
|
||||
Raises:
|
||||
ValueError: If both ``custom_path`` and ``out`` are passed.
|
||||
"""
|
||||
|
||||
if custom_path is not None and out is not None:
|
||||
raise ValueError('custom_path and out are mutually exclusive')
|
||||
|
||||
url = self.file_path
|
||||
|
||||
if custom_path:
|
||||
filename = custom_path
|
||||
else:
|
||||
filename = basename(url)
|
||||
if out:
|
||||
buf = self.bot.request.retrieve(url)
|
||||
out.write(buf)
|
||||
|
||||
self.bot.request.download(url, filename)
|
||||
else:
|
||||
if custom_path:
|
||||
filename = custom_path
|
||||
else:
|
||||
filename = basename(url)
|
||||
|
||||
self.bot.request.download(url, filename)
|
||||
|
|
|
@ -208,6 +208,14 @@ class Request(object):
|
|||
|
||||
return self._parse(result)
|
||||
|
||||
def retrieve(self, url):
|
||||
"""Retrieve the contents of a file by its URL.
|
||||
Args:
|
||||
url:
|
||||
The web location we want to retrieve.
|
||||
"""
|
||||
return self._request_wrapper('GET', url)
|
||||
|
||||
def download(self, url, filename):
|
||||
"""Download a file by its URL.
|
||||
Args:
|
||||
|
@ -218,6 +226,6 @@ class Request(object):
|
|||
The filename within the path to download the file.
|
||||
|
||||
"""
|
||||
buf = self._request_wrapper('GET', url)
|
||||
buf = self.retrieve(url)
|
||||
with open(filename, 'wb') as fobj:
|
||||
fobj.write(buf)
|
||||
|
|
Loading…
Add table
Reference in a new issue