This repository has been archived on 2023-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
python-blog/articles/utils.py

49 lines
1.3 KiB
Python
Raw Normal View History

2021-01-03 21:51:46 +01:00
import re
import html2text
import markdown
from django.conf import settings
2021-01-03 21:51:46 +01:00
from markdown.extensions.codehilite import CodeHiliteExtension
from articles.markdown import LazyLoadingImageExtension
def build_full_absolute_url(request, url):
if request:
return request.build_absolute_uri(url)
else:
return (settings.BLOG["base_url"] + url)[::-1].replace("//", "/", 1)[::-1]
2021-01-03 21:51:46 +01:00
def format_article_content(content):
md = markdown.Markdown(
extensions=[
"extra",
"admonition",
2021-04-05 11:05:42 +02:00
CodeHiliteExtension(linenums=True, guess_lang=False),
2021-01-03 21:51:46 +01:00
LazyLoadingImageExtension(),
]
)
content = re.sub(r"(\s)#(\w+)", r"\1\#\2", content)
return md.convert(content)
def truncate_words_after_char_count(text, char_count):
total_length = 0
text_result = []
for word in text.split():
if len(word) + 1 + total_length > char_count:
break
text_result.append(word)
total_length += len(word) + 1
return " ".join(text_result) + "..."
def get_html_to_text_converter():
converter = html2text.HTML2Text()
converter.ignore_images = True
converter.ignore_links = True
converter.ignore_tables = True
converter.ignore_emphasis = True
return converter