command for optimize news images
This commit is contained in:
parent
b2d70ddbf0
commit
0672bcaef9
39
apps/news/management/commands/news_optimize_images.py
Normal file
39
apps/news/management/commands/news_optimize_images.py
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
# coding=utf-8
|
||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
from utils.methods import get_url_images_in_text
|
||||||
|
from news.models import News
|
||||||
|
from sorl.thumbnail import get_thumbnail
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
SORL_THUMBNAIL_ALIASES = 'news_image'
|
||||||
|
|
||||||
|
def add_arguments(self, parser):
|
||||||
|
parser.add_argument(
|
||||||
|
'-a',
|
||||||
|
'--alias',
|
||||||
|
default=self.SORL_THUMBNAIL_ALIASES,
|
||||||
|
help='Ключ для параметров оптимизации',
|
||||||
|
)
|
||||||
|
|
||||||
|
def optimize(self, text, alias):
|
||||||
|
for image in get_url_images_in_text(text):
|
||||||
|
optimized_image = get_thumbnail(
|
||||||
|
file_=image,
|
||||||
|
**settings.SORL_THUMBNAIL_ALIASES[alias]
|
||||||
|
).url
|
||||||
|
text = text.replace(image, optimized_image)
|
||||||
|
self.stdout.write(self.style.SUCCESS(f'Optimized {image} -> {optimized_image}...\n'))
|
||||||
|
|
||||||
|
return text
|
||||||
|
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
for news in News.objects.all():
|
||||||
|
if not isinstance(news.description, dict):
|
||||||
|
continue
|
||||||
|
news.description = {
|
||||||
|
locale: self.optimize(text, options['alias'])
|
||||||
|
for locale, text in news.description.items()
|
||||||
|
}
|
||||||
|
news.save()
|
||||||
|
|
@ -169,3 +169,9 @@ def section_name_into_index_name(section_name: str):
|
||||||
result = re.findall(re_exp, section_name)
|
result = re.findall(re_exp, section_name)
|
||||||
if result:
|
if result:
|
||||||
return f"{' '.join([word.capitalize() if i == 0 else word for i, word in enumerate(result[:-2])])}"
|
return f"{' '.join([word.capitalize() if i == 0 else word for i, word in enumerate(result[:-2])])}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_url_images_in_text(text):
|
||||||
|
"""Find images urls in text"""
|
||||||
|
import re
|
||||||
|
return re.findall(r'(?:http:|https:)?//.*\.(?:png|jpg|svg)', text)
|
||||||
Loading…
Reference in New Issue
Block a user