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:
Yan 2016-12-18 05:05:00 +03:00 committed by Jannes Höke
parent a37add39f4
commit c3984e1bf1
2 changed files with 35 additions and 9 deletions

View file

@ -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)

View file

@ -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)