本文整理汇总了Python中markdown.Markdown.convert方法的典型用法代码示例。如果您正苦于以下问题:Python Markdown.convert方法的具体用法?Python Markdown.convert怎么用?Python Markdown.convert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类markdown.Markdown
的用法示例。
在下文中一共展示了Markdown.convert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TableMarkupExtensionTest
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
class TableMarkupExtensionTest(unittest.TestCase):
def setUp(self):
self.originalMd = Markdown()
self.md = Markdown([TableMarkupExtension()])
def test_basic(self):
firstPart = "First part with two paragraphs\n\nThe second paragraph\n\n* A list"
secondPart = "Second part"
actual = self.md.convert(
firstPart + \
"\n\n-----\n\n" + \
secondPart)
expectedRe = \
r"^<tr>\s*" + \
r"<td>\s*" + re.escape(self.originalMd.convert(firstPart)) + "\s*</td>\s*" + \
r"<td>\s*" + re.escape(self.originalMd.convert(secondPart)) + "\s*</td>\s*" + \
r"</tr>$"""
self.assertRegex(actual, expectedRe)
def test_beginning_hr_is_ignored(self):
source = "-----\n\nТекст"
expectedRe = r"""^<tr>\s*<td>\s*<p>Текст</p>\s*</td>\s*</tr>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_ending_hr_is_ignored(self):
source = "Текст\n\n-----"
expectedRe = r"""^<tr>\s*<td>\s*<p>Текст</p>\s*</td>\s*</tr>$"""
self.assertRegex(self.md.convert(source), expectedRe)
示例2: test_i18n_always_after_toc
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def test_i18n_always_after_toc(self):
text = '# This is h1'
expected_toc = (
'<div class="toc">'
' <ul>'
' <li><a href="#esto-es-h1">Esto es h1</a></li>'
' </ul>'
'</div>'
)
self.catalog.add(
'This is h1',
'Esto es h1'
)
self.write_po()
md = Markdown(
extensions=['markdown.extensions.toc', 'markdown_i18n'],
extension_configs={
'markdown_i18n': {
'i18n_dir': self.dir,
'i18n_lang': 'es_ES'
}
}
)
md.convert(text)
toc = getattr(md, 'toc', '')
self.assertEqual(clean_xml(toc), clean_xml(expected_toc))
示例3: __init__
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def __init__(self, templatefile, *apifiles, **kwargs):
if len(apifiles) == 0:
raise ValueError("There must be at least one APIBlueprint file "
"specified")
include_comments = kwargs.pop("include_comments", True)
base_class = kwargs.pop("base_class", None)
if base_class is None:
base_class = "rest_framework.test.APITestCase"
self._use_html2text = kwargs.pop("html2text", False)
m = Markdown(extensions=["plueprint"])
m.set_output_format("apiblueprint")
with codecs.open(apifiles[0], "r", "utf-8") as fin:
self._api = m.convert(fin.read())
for f in apifiles[1:]:
with codecs.open(f, "r", "utf-8") as fin:
self._api.merge(m.convert(fin.read()))
env = Environment(loader=FileSystemLoader(templatefile),
autoescape=False, trim_blocks=True,
lstrip_blocks=True,
extensions=("jinja2.ext.loopcontrols",))
env.filters["symbolize"] = self._symbolize
env.filters["html2text"] = self._html2text
self._template = env.get_template("")
self._include_comments = include_comments
self._base_class = base_class[base_class.rfind('.') + 1:]
self._base_module = base_class[:-len(self._base_class) - 1]
self._counter = 1
示例4: HtmlHeaderExtensionTest
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
class HtmlHeaderExtensionTest(unittest.TestCase):
DOCTYPE_AND_META = '^' + \
r"""<!DOCTYPE html>\n""" + \
r"""<meta charset=['"]utf-8['"](>|></meta>| */>)\s*"""
def setUp(self):
self.md = Markdown([HtmlHeaderExtension()])
def test_basic(self):
source = "Текст"
expectedRe = self.DOCTYPE_AND_META + "<p>Текст</p>$"
self.assertRegex(self.md.convert(source), expectedRe)
def test_title_is_inserted_for_1st_level_heading(self):
source = "# Заголовок"
expectedRe = self.DOCTYPE_AND_META + \
"<title>Заголовок</title>\s*" + \
"<h1>Заголовок</h1>$"
self.assertRegex(self.md.convert(source), expectedRe)
def test_title_not_inserted_if_several_headings(self):
source = "# Заголовок 1\n\n# Заголовок 2"
expectedRe = self.DOCTYPE_AND_META + \
"<h1>Заголовок 1</h1>\s*" + \
"<h1>Заголовок 2</h1>\s*$"
self.assertRegex(self.md.convert(source), expectedRe)
def test_title_tags_are_property_stripped(self):
source = "# Заголовок со [ссылкой](http://example.com/) внутри"
expectedRe = self.DOCTYPE_AND_META + "<title>Заголовок со ссылкой внутри</title>"
self.assertRegex(self.md.convert(source), expectedRe)
示例5: __init__
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def __init__(self, info_yaml, basedir=''):
"""Import the solution's info.yaml file."""
f, url_parts = self._open(info_yaml, basedir)
solution_yaml = f.read().decode('utf-8')
self.basedir = urlunparse((url_parts.scheme, url_parts.netloc,
os.path.dirname(url_parts.path),
None, None, None))
# create a markdown converter and modify it to rebase image links
markdown = Markdown()
markdown.inlinePatterns['image_link'] = _RebasedImageLinkPattern(
self.basedir, IMAGE_LINK_RE, markdown)
markdown.inlinePatterns['image_reference'] = _RebasedImageRefPattern(
self.basedir, IMAGE_REFERENCE_RE, markdown)
# import the solution's metadata
info = yaml.load(solution_yaml)
self.id = hashlib.md5(solution_yaml.encode('utf-8')).hexdigest()
self.title = info['name']
self.release = str(info['release'])
if 'logo' in info:
self.logo = self._make_absolute_path(info.get('logo'),
self.basedir)[0]
# in all the following fields, newlines are suppressed because they
# are not rendered properly in Javascript strings by Django
self.short_description = \
markdown.convert(info['short_desc']).replace('\n', '')
self.long_description = \
markdown.convert(info['long_desc']).replace('\n', '')
self.architecture = \
markdown.convert(info['architecture']).replace('\n', '')
self.design_specs = info.get('design_specs', [])
self.heat_template = info['heat_template']
self.env_file = info.get('env_file') # environments are optional
示例6: MarkdownReader
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
class MarkdownReader(Reader):
enabled = bool(Markdown)
file_extensions = ['md', 'markdown', 'mkd', 'mdown']
default_extensions = ['codehilite(css_class=highlight)', 'extra']
def __init__(self, *args, **kwargs):
super(MarkdownReader, self).__init__(*args, **kwargs)
self.extensions = self.settings.get('MD_EXTENSIONS',
self.default_extensions)
self.extensions.append('meta')
self._md = Markdown(extensions=self.extensions)
def _parse_metadata(self, meta):
"""Return the dict containing document metadata"""
output = {}
for name, value in meta.items():
name = name.lower()
if name == "summary":
summary_values = "\n".join(value)
# reset the markdown instance to clear any state
self._md.reset()
summary = self._md.convert(summary_values)
output[name] = self.process_metadata(name, summary)
else:
output[name] = self.process_metadata(name, value[0])
return output
def read(self, source_path):
"""Parse content and metadata of markdown files"""
with pelican_open(source_path) as text:
content = self._md.convert(text)
metadata = self._parse_metadata(self._md.Meta)
return content, metadata
示例7: UrlizeExtensionTest
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
class UrlizeExtensionTest(unittest.TestCase):
def setUp(self):
self.md = Markdown([UrlizeExtension()])
def test_links_in_angle_brackets_processed(self):
source = "<http://yandex.ru/>"
expectedRe = r"""^<p><a href=['"]http://yandex.ru/['"]>http://yandex.ru/</a></p>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_links_starting_with_http_processed(self):
source = "http://example.com/"
expectedRe = r"""^<p><a href=['"]http://example.com/['"]>http://example.com/</a></p>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_links_starting_with_www_processed(self):
source = "www.example.com"
expectedRe = r"""^<p><a href=['"]http://www.example.com['"]>www.example.com</a></p>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_markdown_links_not_messed_up(self):
source = "[](http://yandex.ru/)"
expectedRe = r""" href=['"]http://yandex.ru/['"]"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_manual_links_not_messed_up(self):
source = "<a href='http://yandex.ru/'>Яндекс</a>"
expected = "<p>%s</p>" % source
self.assertEqual(expected, self.md.convert(source))
示例8: ItemTypeExtensionTest
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
class ItemTypeExtensionTest(unittest.TestCase):
def setUp(self):
self.md = Markdown([ItemTypeExtension()])
def test_beginning(self):
source = "* [deferred] элемент списка";
expectedRe = r"""^<ul>\s*<li class="type_deferred">элемент списка</li>\s*</ul>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_middle(self):
source = "* элемент [wait] списка";
expectedRe = r"""^<ul>\s*<li class="type_wait">элемент +списка</li>\s*</ul>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_end(self):
source = "* элемент списка [freetime]";
expectedRe = r"""^<ul>\s*<li class="type_freetime">элемент списка *</li>\s*</ul>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_unknown_is_not_replaced(self):
source = "* элемент [списка]";
expectedRe = r"""^<ul>\s*<li>элемент \[списка\]</li>\s*</ul>$"""
self.assertRegex(self.md.convert(source), expectedRe)
def test_references_not_messed_up(self):
source = "Тестовая [freetime][deferred] ссылка\n\n[deferred]: http://example.com"
expectedRe = r"""^<p>Тестовая <a href=["']http://example.com["']>freetime</a> ссылка</p>$"""
self.assertRegex(self.md.convert(source), expectedRe)
示例9: get_feeds
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def get_feeds(feeds_file, max_age, max_feeds):
opml = lp.parse(feeds_file)
feeds = opml.feeds
feeds = feeds[:max_feeds]
md = Markdown()
filename = "rssdigest.html"
with open(filename, "w") as text_file:
text_file.write(md.convert("# Daily RSS Digest \n----"))
digeststring = "# Daily RSS Digest \n----\n\n"
number_of_feeds = len(feeds)
for index, feed in enumerate(feeds):
feed = feedparser.parse(feed.url)
feedstring = ""
addfeed = False
print("[" + str(index) + "/" + str(number_of_feeds) + "]")
if 'title' in feed.feed:
feedstring += "## " + feed.feed.title + "\n"
for entry in feed.entries:
localtime = time.localtime()
try:
publishedtime = entry.published_parsed
# age in days
age = (time.mktime(localtime) - time.mktime(publishedtime)) / 60 / 60 / 24
if age < max_age:
feedstring += "## ["+entry.title+"]("+entry.link+")\n\n"
if 'description' in entry:
if len(entry.description) < 500:
feedstring += entry.description + "\n\n"
addfeed = True
except:
pass
if not addfeed:
print(feedstring + "No new posts\n")
feedstring += "----\n"
if addfeed:
print(feedstring)
# Append to string
digeststring += feedstring
# Append to file
with open(filename, "a") as text_file:
feedhtml = md.convert(feedstring)
text_file.write(feedhtml)
digesthtml = md.convert(digeststring)
# print("Final: " + digesthtml)
return digesthtml
示例10: getPostMeta
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def getPostMeta(self, postFile):
if not postFile:
return "", {}, ""
postId = postFile.split('/')[-1].split('.')[0]
content = readFile(postFile)
md = Markdown(extensions=["meta"])
md.convert(content.decode('utf-8'))
meta = self.genMeta(md.Meta)
return postId, meta, content
示例11: load_issue
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def load_issue(md_source):
"""Reads an issue from a string-like object containing a Markdown document.
Returns the issue number, preamble and stories.
:param md_source: A string containing the Markdown source of the document.
:returns: Tuple of ``(issue number, preamble, stories)``, where the issue
number is an integer, the preamble is a Markdown string and stories is a
list of dictionaries with keys ``title``, ``body`` and ``link``, which are
strings which should be interpreted as Markdown, Markdown and a URL,
respectively."""
# Just parsing to get metadata
parser = Markdown(extensions=["markdown.extensions.meta"])
parser.convert(md_source)
try:
issue_no = int("".join(parser.Meta["issue"]))
except (ValueError, KeyError):
raise ParseError("No issue number present")
# Split document according to level 1 headings (only using # style at BOL).
# Heading group matches will be in elements 1, 3, 5, etc. (so 0, 2, 4, and
# so on are sections)
try:
_, no_meta = md_source.split("\n\n", 1)
except ValueError:
raise ParseError("No preamble after the metadata!")
heading_re = re.compile("\n#([^\n]+)\n")
sections = heading_re.split(no_meta)
if len(sections) <= 3:
raise ParseError("Need more than one section (preamble + at least one story)")
preamble = sections[0]
if not preamble.strip():
raise ParseError("Preamble is empty")
# Process stories
stories = []
for heading_md, story in zip(sections[1::2], sections[2::2]):
lines = story.strip().split("\n")
if not lines:
raise ParseError('Story with heading "{}" is empty'.format(heading_md))
# This is the body of the story
remainder = "\n".join(lines[:-1])
# "Learn more" link should be last line of the story. Last line is
# stripped during processing otherwise. This is a little magic (I
# probably should *enforce* a specific format), but whatever.
link_line = lines[-1]
parsed_ll = BeautifulSoup(markdown(link_line), "lxml")
elem = parsed_ll.select_one("a[href]")
if elem is None:
raise ParseError('Could not find "learn more" link for "{}"'.format(heading_md))
parsed_link = elem["href"]
stories.append({"title": heading_md, "body": remainder, "link": parsed_link})
return (issue_no, preamble, stories)
示例12: POST
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def POST(self):
web.header('Content-Type', 'application/json')
try:
param = json.loads(web.data())
try:
postId = str(int(param['postId']))
postContent = param['postContent'].encode('utf-8')
except:
logging.error("%s", traceback.format_exc())
return json.dumps(InputError)
if os.path.exists('%s/frontend/md/%s.md' % (ProjectPath, postId)):
oldStatus = 'public'
postId, oldMeta, tmp = self.getPostMeta('%s/frontend/md/%s.md' % (ProjectPath, postId))
else:
oldStatus = 'private'
if os.path.exists('%s/frontend/md/%s.md_' % (ProjectPath, postId)):
postId, oldMeta, tmp = self.getPostMeta('%s/frontend/md/%s.md_' % (ProjectPath, postId))
else:
oldMeta = {}
try:
md = Markdown(extensions=["meta"])
md.convert(postContent.decode('utf-8'))
meta = self.genMeta(md.Meta)
for key in ["category", "tags", "date", "title", "status"]:
if not meta.has_key(key) or not meta[key]:
raise ValueError("input error")
if key == "status" and meta[key] not in ["public", "private"]:
raise ValueError("input error")
except:
logging.error("%s", traceback.format_exc())
return json.dumps(MetaError)
status = meta['status'] if meta.has_key('status') else 'private'
os.system('rm -rf %s/frontend/md/%s.md*' % (ProjectPath, postId))
os.system('rm -rf %s/frontend/post/%s.html*' % (ProjectPath, postId))
isLatest = self.isLatestPost(postId, status)
writeFile(self.getFilename('md', postId, status), postContent)
writeFile(self.getFilename('post', postId, status), self.genPostPage(postId, postContent, meta, isLatest and status == 'public'))
if isLatest:
writeFile("%s/frontend/home.html" % (ProjectPath), self.genHomePage())
if oldStatus != status:
writeFile('%s/frontend/archive.html' % (ProjectPath), self.genArchivePage())
self.genSitemap()
if oldStatus != status or oldMeta != meta:
self.updateIndex(oldMeta,
self.getFilename('md', postId, oldStatus),
meta,
self.getFilename('md', postId, status))
return json.dumps(Success)
except:
logging.error("SavePost get exception: %s", traceback.format_exc())
return json.dumps(SaveError)
示例13: _get_slide_io2012
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def _get_slide_io2012(self, contents=None, extensions=[]):
""" io-2012 style """
md = Markdown(extensions=extensions)
splits = [
{'horizon': '---', 'style': 'none'},
{'horizon': '___', 'style': 'smaller'},
{'horizon': '***', 'style': 'fill'}
]
styles = []
for split in splits:
styles.append(split['style'])
horizon = '\n' + split['horizon'] + '\n'
contents = contents.replace(horizon, '\n---\n' + split['style'] + '\n')
pages = contents.split('\n---\n')
# from pages to slides
slides = []
for page in pages:
sections = page.split('\n\n', 2)
slide = {}
if not sections[0] in styles:
if len(sections) > 2:
sections[1] += '\n\n' + sections[2]
sections.insert(0, 'none')
slide['style'] = sections[0]
if len(sections) > 1:
slide['hgroup'] = sections[1]
if len(sections) > 2:
slide['article'] = sections[2]
slides.append(slide)
# from slides to html
html = '\n'
for slide in slides:
html += '<slide>\n'
if slide.has_key('hgroup'):
html += '<hgroup>\n'
html += md.convert(slide['hgroup']) + '\n'
html += '</hgroup>\n'
if slide.has_key('article'):
html += '<article class="' + slide['style'] + '">\n'
html += md.convert(slide['article']) + '\n'
html += '</article>\n'
html += '</slide>\n\n'
# from comment out to presener note
html = html.replace('\n<!--\n', '\n<aside class="note">\n')
html = html.replace('\n-->\n', '\n</aside>\n')
return html
示例14: render_view
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
def render_view(t_path, view='static', values=None):
template_values={}
if view == 'logs':
md = Markdown()
for log in values[0]:
log.display = md.convert(log.content)
template_values = {
'logs': values[0],
'older': values[1],
'newer': values[2],
'spacer': values[1] and values[2],
}
if view == 'stufflist':
template_values = {
'stufflist':values,
}
if view == 'logentry':
template_values = {
'log':values,
}
if view == 'stuffentry':
md = Markdown()
for log in values[1][0]:
log.display = md.convert(log.content)
template_values = {
'stuff':values[0],
'logs': values[1][0],
'older': values[1][1],
'newer': values[1][2],
'spacer': values[1][1] and values[1][2],
}
if view == 'info':
md = Markdown()
conv_info = md.convert(values)
template_values = {'tt': conv_info }
if view == 'editlogs':
template_values = {'logs': values}
if view == 'editstuff':
template_values = {'stufflist': values}
if view == 'edittt':
template_values = {'tt': values}
if view == 'add':
template_values = {'numbers': values }
path = os.path.join(os.path.dirname(__file__),t_path)
template_values['admin'] = users.is_current_user_admin()
return template.render(path,template_values)
示例15: CodeNewlinesRemovalExtensionTest
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import convert [as 别名]
class CodeNewlinesRemovalExtensionTest(unittest.TestCase):
def setUp(self):
self.md = Markdown([CodeNewlinesRemovalExtension()])
def test_basic(self):
source = '''<pre><code>\nНекоторый код, напечатанный на новой строке\n</code></pre>'''
expected = '''<pre><code>Некоторый код, напечатанный на новой строке</code></pre>'''
self.assertEqual(expected, self.md.convert(source))
def test_attributes_are_preserved(self):
source = '''<pre id='id'><code class='class'>\n...\n</code></pre>'''
expected = '''<pre id='id'><code class='class'>...</code></pre>'''
self.assertEqual(expected, self.md.convert(source))