view bitsyblog/utils.py @ 131:2d944e8f24e9

py3
author Jeff Hammel <k0scist@gmail.com>
date Mon, 28 Dec 2020 19:22:23 +0000
parents 73434c2db108
children
line wrap: on
line source

"""utlity functions for bitsyblog"""

import cgi
import datetime
import os

import docutils
import docutils.core

from docutils.utils import SystemMessage

# format to uniquely label blog posts
timeformat = ( 'YYYY', 'MM', 'DD', 'HH', 'MM', 'SS' )
timestamp = '%Y%m%d%H%M%S' # strftime representation


def ReST2html(string):
    """renders a string with restructured text"""

    settings = { 'report_level': 5 }
    string = string.strip()
    try:
        parts = docutils.core.publish_parts(string,
                                            writer_name='html',
                                            settings_overrides=settings)
        body = parts['body']
    except (SystemMessage, UnicodeError) as e:
        lines = [ cgi.escape(i.strip()) for i in string.split('\n') ]
        body = '<br/>\n'.join(lines)
    return body


def validate_css(css):
    # DEPRECATED!  Just return `True` for now
    return True


def date(datestamp):
    datestamp = os.path.split(datestamp)[-1]
    retval = []
    for i in timeformat:
        retval.append(int(datestamp[:len(i)]))
        datestamp = datestamp[len(i):]
    return datetime.datetime(*retval)

def datestamp(date=None):
    if isinstance(date, float):
        date = datetime.datetime.fromtimestamp(date)
    if date is None:
        date = datetime.datetime.now()
    return date.strftime(timestamp)