Source code for fireblog.utils
from markdown import markdown
from fireblog.models import DBSession, Tags, Users
from fireblog.htmltruncate import truncate as truncate_html
from fireblog.settings import settings_dict
from fireblog.dogpile_region import region
import arrow
import transaction
[docs]def urlify(string: str) -> str:
"""Replace spaces with dashes. We don't do anything else like urlencoding,
as pyramid does that already for us."""
return string.replace(' ', '-')
[docs]def get_anonymous_userid() -> str:
"""Returns the userid of the unique anonymous id. This userid is used
whenever somneone wants to post a comment anonymously, as all comments
must be associated with some author.
If the anonymous user doesn't exist in the db, they are created on the
fly."""
anon_email = 'anonymous@example.com'
user = DBSession.query(Users.userid).filter_by(userid=anon_email).first()
with transaction.manager:
if not user:
# Create user
user = Users(userid=anon_email)
DBSession.add(user)
return anon_email
@region.cache_on_arguments()
[docs]def to_markdown(input_text):
'''Basic wrapper around the markdown library. This function accepts
markdown and returns html. It enables extensions that allow for code
highlighting and writing code using fenced code blocks.'''
extensions = ['markdown.extensions.codehilite',
'markdown.extensions.fenced_code']
res = markdown(input_text, extensions=extensions)
return res
def _turn_tag_object_into_sorted_list(tag_object):
tags = sorted([t.tag for t in tag_object])
return tags
[docs]def turn_tag_object_into_html_string_for_display(request, tag_object):
tags = _turn_tag_object_into_sorted_list(tag_object)
if not tags:
return ''
for e, tag in enumerate(tags):
tags[e] = "<a href = {link}>{tag}</a>".format(
tag=tag, link=request.route_url('tag_view', tag_name=tag))
return ', '.join(tags)
[docs]def create_post_list_from_posts_obj(request, post_obj):
LENGTH_OF_EACH_POST_TO_INCLUDE_IN_ALL_POST_VIEW = settings_dict[
'fireblog.all_view_post_len']
l = LENGTH_OF_EACH_POST_TO_INCLUDE_IN_ALL_POST_VIEW
res = []
code_styles = False # Is true if we need to include pygments css
# in the page
for post in post_obj:
to_append = {}
to_append["id"] = post.id
to_append["name"] = post.name
html = to_markdown(post.markdown)
html = truncate_html(html, l, ellipsis='...')
to_append["html"] = html
to_append["date"] = format_datetime(post.created)
res.append(to_append)
if not code_styles and 'class="codehilite"' in to_append["html"]:
code_styles = True
return res, code_styles