Skip to content

Instantly share code, notes, and snippets.

@shuhaowu
Created October 18, 2012 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuhaowu/3914323 to your computer and use it in GitHub Desktop.
Save shuhaowu/3914323 to your computer and use it in GitHub Desktop.
MarkdownProperty for Riakkit
from riakkit import DictProperty, BaseProperty
import markdown
from lxml.html.clean import Cleaner
_cleaner = Cleaner(add_nofollow=True, style=True)
_markdown = markdown.Markdown(safe_mode="escape")
class MarkdownProperty(BaseProperty):
class MD(DictProperty.DotDict):
def get(self, markdown):
return self.markdown if markdown else self.html
@staticmethod
def mdconverter(text):
"""Converts some text to a DotDict object with markdown and html as
attribute. Note that the argument text is unstripped. All security
have to go through this converter.
Args:
text: The input text probably directly submitted by the client.
Returns:
A DocDict object with an html field.
"""
if isinstance(text, DictProperty.DotDict):
return text
elif isinstance(text, dict):
return MarkdownProperty.MD(text)
md = text
# TODO: https://github.com/waylan/Python-Markdown/issues/101#issuecomment-5882555
html = _markdown.convert(md)
if len(html) > 0:
html = _cleaner.clean_html(html)
# TODO: Process Youtube Link
return MarkdownProperty.MD({"markdown" : md, "html" : html})
def __init__(self, mdconverter=None, **kwargs):
BaseProperty.__init__(self, **kwargs)
if mdconverter is not None:
self.mdconverter = mdconverter
def standardize(self, value):
value = BaseProperty.standardize(self, value)
return self.mdconverter(value)
def convertFromDb(self, value):
value = BaseProperty.convertFromDb(self, value)
if value is None:
return MarkdownProperty.MD({"markdown" : "", "html" : ""})
return MarkdownProperty.MD(value)
def defaultValue(self):
return MarkdownProperty.MD({"markdown" : "", "html" : ""})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment