Sorting by date

This commit is contained in:
Digital Studium 2023-10-14 13:53:51 +03:00
parent 2c30a3bb30
commit d29570739b
1 changed files with 50 additions and 42 deletions

View File

@ -12,7 +12,6 @@ import markdown2
import fire
import minify_html
from common.functions import *
@ -21,7 +20,8 @@ def load_translations(file_path, _dict):
reader = csv.DictReader(f, delimiter='|') #
for row in reader: # проходим по строкам csv, каждая из которых является словарём
_dict[row['id']] = row # добавляем ключ - значение ключа id, значение - словарь row
del row['id'] # удаляем ключ по названием "id" из словаря row, так как его значение уже является ключом в словаре _dict
del row[
'id'] # удаляем ключ по названием "id" из словаря row, так как его значение уже является ключом в словаре _dict
# Функции, доступные в теме
@ -29,20 +29,25 @@ def translate(id, language):
global translations
return translations[id][language]
translations = {} # здесь будут переводы от темы и от сайта
config = yaml.safe_load(read_file('config.yaml')) # Чиатем конфиг сайта
config = yaml.safe_load(read_file('config.yaml')) # Читаем конфиг сайта
running = False # нужно для проверки
# класс для watchdog.
# При обнаружении изменений в папках content и themes/{config['theme']}, перегенерировать папку public
# класс для watchdog
# Во время разработки, при обнаружении изменений в папках content и themes/{config['theme']},
# перегенерировать папку public
class Develop(FileSystemEventHandler):
def on_modified(self, event):
def on_modified(self, event):
print(f'event type: {event.event_type} path : {event.src_path}')
franca()
def on_created(self, event):
def on_created(self, event):
print(f'event type: {event.event_type} path : {event.src_path}')
franca()
def on_deleted(self, event):
def on_deleted(self, event):
print(f'event type: {event.event_type} path : {event.src_path}')
franca()
@ -50,14 +55,14 @@ class Develop(FileSystemEventHandler):
# Функция для запуска разработки
def develop(prod):
global running
if not prod and not running:
if not prod and not running:
event_handler = Develop()
observer = Observer()
observer.schedule(event_handler, path='content', recursive=True)
observer.schedule(event_handler, path='assets', recursive=True)
observer.schedule(event_handler, path='static', recursive=True)
observer.schedule(event_handler, path='config.yaml')
observer.schedule(event_handler, path=f"themes/{config['theme']}", recursive=True)
observer.schedule(event_handler, path='content', recursive=True)
observer.schedule(event_handler, path='assets', recursive=True)
observer.schedule(event_handler, path='static', recursive=True)
observer.schedule(event_handler, path='config.yaml')
observer.schedule(event_handler, path=f"themes/{config['theme']}", recursive=True)
observer.start()
running = True
try:
@ -65,10 +70,10 @@ def develop(prod):
except KeyboardInterrupt:
pass
# Функция для генерации сайта
def franca(prod=False):
# if prod is False, then redefine config.base_url
if prod is False:
if not prod:
config['base_url'] = "http://127.0.0.1:8000"
# Load theme's jinja templates
templates = Environment(loader=FileSystemLoader(
@ -103,47 +108,49 @@ def franca(prod=False):
"content", "public").rstrip(".md")
os.makedirs(post_path, exist_ok=True)
content = markdown2.markdown(post_data.content, extras=['fenced-code-blocks'])
description = content.partition('<!--more-->')[0]
content = "{% import 'shortcodes.j2' as shortcodes %}" + content
url = post_path.replace(f"public/{language}", "")
section = "/" if len(url.split('/')) == 2 else url.split('/')[1]
date = post_data['date']
posts[language].setdefault(date, {})
posts[language][date].setdefault(section, {})
posts[language].setdefault(section, {})
posts[language][section][url] = {
posts[language][date][section][url] = {
'title': post_data['title'],
'description': description,
'date': post_data['date'],
'date': date,
'content': templates.from_string(content).render()
}
image = post_data.get('image', None)
if image:
os.makedirs(os.path.dirname(f'public{image}'), exist_ok=True)
os.makedirs(os.path.dirname(f'public{image}'), exist_ok=True)
filename = image.split('/')[-1].split('.')[0]
create_thumbnail(f'assets{image}', f'public/images/{filename}_600.jpg', 600)
posts[language][section][url]['image'] = f'/images/{filename}_600.jpg'
create_thumbnail(f'assets{image}', f'public/images/{filename}_600.jpg', 600)
posts[language][date][section][url]['image'] = f'/images/{filename}_600.jpg'
create_thumbnail(f'assets{image}', f'public/images/{filename}_400.jpg', 400)
posts[language][section][url]['thumbnail'] = f'/images/{filename}_400.jpg'
create_thumbnail(f'assets{image}', f'public/images/{filename}_400.jpg', 400)
posts[language][date][section][url]['thumbnail'] = f'/images/{filename}_400.jpg'
posts[language] = dict(sorted(posts[language].items(), reverse=True))
for section, urls in posts[language].items():
if section != "/":
html = base.render(config=config, section=section,
language=language, posts=posts)
for date, sections in posts[language].items():
for section, urls in sections.items():
if section != "/":
html = base.render(config=config, section=section,
language=language, posts=posts)
write_file(f"public/{language}/{section}/index.html", minify_html.minify(html, minify_js=True))
write_file(f"public/{language}/{section}/index.html", minify_html.minify(html, minify_js=True))
for url, post in urls.items():
html = base.render(config=config, post=post,
language=language, url=url, posts=posts)
for url, post in urls.items():
html = base.render(config=config, post=post,
language=language, url=url, posts=posts)
write_file(f"public/{language}{url}/index.html", minify_html.minify(html, minify_js=True))
write_file(f"public/{language}{url}/index.html", minify_html.minify(html, minify_js=True))
html = base.render(config=config, posts=posts,
language=language, home=True)
@ -157,29 +164,30 @@ def franca(prod=False):
if 'css_includes' in config:
for include in config['css_includes']:
css = read_file(f"themes/{config['theme']}/static/css/{include}")
minify_css(f'public/css/{include}', css)
minify_css(f'public/css/{include}', css)
if 'js_includes' in config:
for include in config['js_includes']:
copy_file(f"themes/{config['theme']}/static/js/{include}", 'public/js/')
copy_file(f"themes/{config['theme']}/static/js/{include}", 'public/js/')
# copy css/images from site static folder
# copy css/images from site static folder
if 'custom_css' in config:
shutil.copytree('static/css', 'public/css', dirs_exist_ok=True)
copy_file('static/logo.svg', 'public/')
copy_file('static/favicon.ico', 'public/')
# Write main index.html
html = index.render(config=config)
write_file('public/index.html', minify_html.minify(html, minify_js=True))
# Write robots.txt
robots_content = "User-agent: *"
robots_content = "User-agent: *"
if not config.get('search_engines', None) == "allow":
robots_content += "\nDisallow: /"
write_file('public/robots.txt', robots_content)
if 'pagefind' in config:
os.system("npx pagefind --source public") # build search index
if prod:
if 'pagefind' in config:
os.system("npx pagefind --source public") # build search index
develop(prod)