Skip to content

Commit

Permalink
Download changed (#459)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
OctoNezd authored and jh0ker committed Dec 18, 2016
1 parent a37add3 commit c3984e1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
34 changes: 26 additions & 8 deletions telegram/file.py
Expand Up @@ -65,17 +65,35 @@ def de_json(data, bot):

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
if out:
buf = self.bot.request.retrieve(url)
out.write(buf)

else:
filename = basename(url)
if custom_path:
filename = custom_path
else:
filename = basename(url)

self.bot.request.download(url, filename)
self.bot.request.download(url, filename)
10 changes: 9 additions & 1 deletion telegram/utils/request.py
Expand Up @@ -208,6 +208,14 @@ def post(self, url, data, timeout=None):

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:
Expand All @@ -218,6 +226,6 @@ def download(self, url, filename):
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)

0 comments on commit c3984e1

Please sign in to comment.