add API for different markup languages

This commit is contained in:
posativ 2012-10-20 18:12:02 +02:00
parent 9aeed1a47e
commit 487d76ba61
4 changed files with 51 additions and 12 deletions

View File

@ -31,11 +31,12 @@ from werkzeug.serving import run_simple
from werkzeug.wrappers import Request, Response from werkzeug.wrappers import Request, Response
from werkzeug.exceptions import HTTPException, NotFound, InternalServerError from werkzeug.exceptions import HTTPException, NotFound, InternalServerError
from isso import admin, comment, db, utils from isso import admin, comment, db
from isso.utils import determine, import_object, RegexConverter, IssoEncoder
# override default json :func:`dumps`. # override default json :func:`dumps`.
_dumps = json.dumps _dumps = json.dumps
setattr(json, 'dumps', lambda obj, **kw: _dumps(obj, cls=utils.IssoEncoder, **kw)) setattr(json, 'dumps', lambda obj, **kw: _dumps(obj, cls=IssoEncoder, **kw))
# yep. lazy. # yep. lazy.
url = lambda path, endpoint, methods: Rule(path, endpoint=endpoint, methods=methods) url = lambda path, endpoint, methods: Rule(path, endpoint=endpoint, methods=methods)
@ -50,7 +51,7 @@ url_map = Map([
url('/comment/<re(".+"):path>/new', 'comment.create', ['POST']), url('/comment/<re(".+"):path>/new', 'comment.create', ['POST']),
url('/comment/<re(".+"):path>/<int:id>', 'comment.get', ['GET']), url('/comment/<re(".+"):path>/<int:id>', 'comment.get', ['GET']),
url('/comment/<re(".+"):path>/<int:id>', 'comment.modify', ['PUT', 'DELETE']), url('/comment/<re(".+"):path>/<int:id>', 'comment.modify', ['PUT', 'DELETE']),
], converters={'re': utils.RegexConverter}) ], converters={'re': RegexConverter})
class Isso: class Isso:
@ -67,11 +68,13 @@ class Isso:
self.__dict__.update(dict((k, v) for k, v in conf.iteritems() if k.isupper())) self.__dict__.update(dict((k, v) for k, v in conf.iteritems() if k.isupper()))
self.signer = URLSafeTimedSerializer(self.SECRET_KEY) self.signer = URLSafeTimedSerializer(self.SECRET_KEY)
self.HOST = utils.determine(self.HOST) self.HOST = determine(self.HOST)
if self.SQLITE: if self.SQLITE:
self.db = db.SQLite(self) self.db = db.SQLite(self)
self.markup = import_object(conf.get('MARKUP', 'isso.markup.Markdown'))(conf)
def sign(self, obj): def sign(self, obj):
return self.signer.dumps(obj) return self.signer.dumps(obj)

View File

@ -21,7 +21,7 @@ def create(app, environ, request, path):
except ValueError: except ValueError:
return abort(400) return abort(400)
rv.text = utils.markdown(rv.text) rv.text = app.markup.convert(rv.text)
response = Response(json.dumps(rv), 201, content_type='application/json') response = Response(json.dumps(rv), 201, content_type='application/json')
response.set_cookie('session', app.signer.dumps([path, rv.id]), max_age=app.MAX_AGE) response.set_cookie('session', app.signer.dumps([path, rv.id]), max_age=app.MAX_AGE)
return response return response
@ -35,9 +35,9 @@ def get(app, environ, request, path, id=None):
if isinstance(rv, list): if isinstance(rv, list):
for item in rv: for item in rv:
item.text = utils.markdown(item.text) item.text = app.markup.convert(item.text)
else: else:
rv.text = utils.markdown(rv.text) rv.text = app.markup.convert(rv.text)
return Response(json.dumps(rv), 200, content_type='application/json') return Response(json.dumps(rv), 200, content_type='application/json')

34
isso/markup.py Normal file
View File

@ -0,0 +1,34 @@
# XXX: BBCode -- http://pypi.python.org/pypi/bbcode
import abc
try:
import misaka
except ImportError:
misaka = None # NOQA
class Markup:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __init__(self, conf):
return
@abc.abstractmethod
def convert(self, text):
return text
class Markdown(Markup):
def __init__(self, conf):
if misaka is None:
raise ImportError("Markdown requires 'misaka' lib!")
return
def convert(self, text):
return misaka.html(text, extensions = misaka.EXT_STRIKETHROUGH \
| misaka.EXT_SUPERSCRIPT | misaka.EXT_AUTOLINK \
| misaka.HTML_SKIP_HTML | misaka.HTML_SKIP_IMAGES | misaka.HTML_SAFELINK)

View File

@ -9,7 +9,6 @@ import httplib
import urlparse import urlparse
import contextlib import contextlib
import misaka
import werkzeug.routing import werkzeug.routing
from isso.models import Comment from isso.models import Comment
@ -48,7 +47,10 @@ def determine(host):
return (rv.netloc + ':443') if rv.scheme == 'https' else rv.netloc return (rv.netloc + ':443') if rv.scheme == 'https' else rv.netloc
def markdown(text): def import_object(name):
return misaka.html(text, if '.' not in name:
extensions = misaka.EXT_STRIKETHROUGH | misaka.EXT_SUPERSCRIPT | misaka.EXT_AUTOLINK \ return __import__(name)
| misaka.HTML_SKIP_HTML | misaka.HTML_SKIP_IMAGES | misaka.HTML_SAFELINK)
parts = name.split('.')
obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
return getattr(obj, parts[-1])