Created
October 18, 2012 19:38
-
-
Save shuhaowu/3914323 to your computer and use it in GitHub Desktop.
MarkdownProperty for Riakkit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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