Added downloading thumbnails to file
This commit is contained in:
@@ -103,3 +103,31 @@ class File(List, Find, Create, Post, Update, Delete, Replace):
|
||||
api=api)
|
||||
return thumbnail.link
|
||||
|
||||
def stream_thumb_to_file(self, directory, desired_size, api=None):
|
||||
"""Streams a thumbnail to a file.
|
||||
|
||||
@param directory: the directory to save the file to.
|
||||
@param desired_size: thumbnail size
|
||||
@return: the absolute path of the downloaded file.
|
||||
"""
|
||||
|
||||
api = api or self.api
|
||||
thumb_link = self.thumbnail_file(desired_size, api=api)
|
||||
|
||||
if thumb_link is None:
|
||||
raise ValueError("File {} has no thumbnail of size {}"
|
||||
.format(self._id, desired_size))
|
||||
|
||||
root, ext = os.path.splitext(self.file_path)
|
||||
thumb_fname = "{0}-{1}.jpg".format(root, desired_size)
|
||||
|
||||
# thumb is now a dict like:
|
||||
# {'content_type': 'image/jpeg', 'height': 160, 'length': 5846,
|
||||
# 'link': 'https://storage.googleapis.com/asdlajsdhaukihuwefiuh',
|
||||
# 'width': 160, 'size': 'b', 'file_path': '65b526639295c0dd9dc99cf54a0a606cd4924f1d-b.jpg',
|
||||
# 'md5': '--', 'format': 'jpg'},
|
||||
|
||||
thumb_path = os.path.abspath(os.path.join(directory, thumb_fname))
|
||||
utils.download_to_file(thumb_link, thumb_path)
|
||||
|
||||
return thumb_path
|
||||
|
||||
@@ -2,6 +2,8 @@ import json
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from contextlib import closing
|
||||
import requests
|
||||
|
||||
try:
|
||||
from urllib.parse import urlencode
|
||||
@@ -107,3 +109,12 @@ def remove_none_attributes(attributes):
|
||||
for k, v in attributes.items() if k is not None and v is not None)
|
||||
else:
|
||||
return attributes
|
||||
|
||||
|
||||
def download_to_file(url, filename, chunk_size=10 * 1024):
|
||||
"""Downloads a file via HTTP(S) directly to the filesystem."""
|
||||
|
||||
with closing(requests.get(url, stream=True, verify=True)) as req, \
|
||||
open(filename, 'wb') as outfile:
|
||||
for block in req.iter_content(chunk_size=chunk_size):
|
||||
outfile.write(block)
|
||||
|
||||
Reference in New Issue
Block a user