gault-millau/apps/news/management/commands/news_optimize_images.py
2020-01-14 17:17:55 +03:00

70 lines
2.4 KiB
Python

# coding=utf-8
from django.core.management.base import BaseCommand
from django.conf import settings
from utils.methods import get_url_images_in_text, get_page_size_by_url
from news.models import News
from sorl.thumbnail import get_thumbnail
class Command(BaseCommand):
SORL_THUMBNAIL_ALIASES = 'news_description'
IMAGE_MAX_SIZE_IN_BYTES = 1048576 # ~ 1mb
def add_arguments(self, parser):
parser.add_argument(
'-a',
'--alias',
default=self.SORL_THUMBNAIL_ALIASES,
help='Ключ для параметров оптимизации',
)
parser.add_argument(
'-s',
'--size',
default=self.IMAGE_MAX_SIZE_IN_BYTES,
help='Максимальный размер файла в байтах',
type=int
)
def optimize(self, text, alias, max_size):
"""optimize news images"""
for image in get_url_images_in_text(text):
size, width, height = get_page_size_by_url(image)
if size < max_size:
continue
percents = round(max_size / (size * 0.01))
width = round(width * percents / 100)
height = round(height * percents / 100)
optimized_image = get_thumbnail(
file_=image,
geometry_string=f'{width}x{height}',
upscale=False
).url
text = text.replace(image, optimized_image)
self.stdout.write(self.style.SUCCESS(f'Optimized {image} -> {optimized_image}\n'
f'Quality [{percents}%]\n'))
return text
def handle(self, *args, **options):
alias = options['alias']
size = options['size']
if alias not in settings.SORL_THUMBNAIL_ALIASES:
self.stdout.write(self.style.ERROR(f'{alias} not found in alias'))
return
self.optimize('https://upload.wikimedia.org/wikipedia/commons/b/b9/Pizigani_1367_Chart_1MB.jpg',
'news_description', size)
# for news in News.objects.all():
# if not isinstance(news.description, dict):
# continue
# news.description = {
# locale: self.optimize(text, alias, size)
# for locale, text in news.description.items()
# }
# news.save()