''' PClinks Extension for Python-Markdown ====================================== Converts [[type:id]] to relative links. Based on . Original code Copyright [Waylan Limberg](http://achinghead.com/). License: [BSD](https://opensource.org/licenses/bsd-license.php) ''' from markdown.extensions import Extension from markdown.inlinepatterns import InlineProcessor import xml.etree.ElementTree as etree from flask import url_for, render_template from app.models.poll import Poll class PCLinkExtension(Extension): def __init__(self, **kwargs): self.config = { # 'base_url': ['/', 'String to append to beginning or URL.'], # 'end_url': ['/', 'String to append to end of URL.'], # 'html_class': ['pclink', 'CSS hook. Leave blank for none.'], } super().__init__(**kwargs) def extendMarkdown(self, md): self.md = md # append to end of inline patterns PCLINK_RE = r'\[\[([a-z]+):\W?(\w+)\]\]' pclinkPattern = PCLinksInlineProcessor(PCLINK_RE, self.getConfigs()) pclinkPattern.md = md md.inlinePatterns.register(pclinkPattern, 'pclink', 75) class PCLinksInlineProcessor(InlineProcessor): def __init__(self, pattern, config): super().__init__(pattern) self.config = config self.handles = { 'poll': handlePoll, } def handleMatch(self, m, data): link_type = m.group(1).strip() if link_type in self.handles: content_id = m.group(2).strip() a = self.handles[link_type](content_id, data) else: a = '' return a, m.start(0), m.end(0) def handlePoll(content_id, context): print(context) if not context.startswith("[[") or not context.endswith("]]"): return "[Sondage invalide]" try: id = int(content_id) except ValueError: return "[ID du sondage invalide]" poll = Poll.query.get(content_id) if poll is None: return "[Sondage non trouvé]" html = render_template('widgets/poll.html', poll=poll) html = html.replace('\n', '') # Needed to avoid lots of
due to etree return etree.fromstring(html)