本文整理匯總了Python中markdown.Markdown方法的典型用法代碼示例。如果您正苦於以下問題:Python markdown.Markdown方法的具體用法?Python markdown.Markdown怎麽用?Python markdown.Markdown使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類markdown
的用法示例。
在下文中一共展示了markdown.Markdown方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: on_page_content
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def on_page_content(
self, html: str, page: Page, config: MkDocsConfig, files: Files
):
if str(page.file.abs_src_path).endswith("ipynb") and not (
"markdown.extensions.md_in_html" in config["markdown_extensions"]
or "markdown.extensions.extra" in config["markdown_extensions"]
):
log.debug(f"Re-rendering page with markdown in divs: {page}")
extensions = [
_RelativePathExtension(page.file, files),
"markdown.extensions.md_in_html",
] + config["markdown_extensions"]
md = markdown.Markdown(
extensions=extensions, extension_configs=config["mdx_configs"] or {}
)
html = md.convert(page.markdown)
page.toc = get_toc(getattr(md, "toc_tokens", []))
return html
示例2: pre_save
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def pre_save(self, model_instance, add):
instance = model_instance
value = None
for attr in self.source.split('.'):
value = getattr(instance, attr)
instance = value
if value is None or value == '':
return value
extensions = [
'markdown.extensions.extra',
'markdown.extensions.codehilite',
]
md = markdown.Markdown(extensions=extensions)
value = md.convert(value)
value = bleach_value(value)
value = bleach.linkify(value)
setattr(model_instance, self.attname, value)
return value
示例3: main
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", help="Output pickle file path",
default=None)
parser.add_argument("input", help="Input API Blueprint file")
args = parser.parse_args()
with codecs.open(args.input, "r", "utf-8") as fin:
txt = fin.read()
m = Markdown(extensions=["plueprint"])
m.set_output_format("apiblueprint")
api = m.convert(txt)
if args.output is not None:
with open(args.output, "wb") as fout:
pickle.dump(api, fout, protocol=-1)
else:
print(api)
print("Resource groups:")
for g in api:
print(" %s" % g)
print(" Resources:")
for r in g:
print(" %s" % r)
print(" Actions:")
for a in r:
print(" %s" % a)
示例4: main
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def main():
m = Markdown(extensions=["plueprint"])
m.set_output_format("apiblueprint")
tests_dir = os.path.join(os.path.dirname(__file__), "api-blueprint",
"examples")
skip_number = 0
index = 0
for doc in sorted(os.listdir(tests_dir)):
if os.path.splitext(doc)[1] != ".md" or doc == "README.md":
continue
index += 1
if index <= skip_number:
continue
with codecs.open(os.path.join(tests_dir, doc), "r", "utf-8") as fin:
txt = fin.read()
api = m.convert(txt)
print("-- %s --" % doc)
print(api)
try:
api[">"].print_resources()
except KeyError:
pass
print("Actions:")
for action in api["/"]:
print(action)
示例5: run
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def run(): # pragma: no cover
"""Run Markdown from the command line."""
# Parse options and adjust logging level if necessary
options, logging_level = parse_options()
if not options:
sys.exit(2)
logger.setLevel(logging_level)
console_handler = logging.StreamHandler()
logger.addHandler(console_handler)
if logging_level <= WARNING:
# Ensure deprecation warnings get displayed
warnings.filterwarnings('default')
logging.captureWarnings(True)
warn_logger = logging.getLogger('py.warnings')
warn_logger.addHandler(console_handler)
# Run
markdown.markdownFromFile(**options)
示例6: handleMatch
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def handleMatch(self, match: Match[str]) -> Element:
rendered = render_tex(match.group('body'), is_inline=True)
if rendered is not None:
# We need to give Python-Markdown an ElementTree object, but if we
# give it one with correctly stored XML namespaces, it will mangle
# everything when serializing it. So we play this stupid game to
# store xmlns as a normal attribute. :-[
assert ' zulip-xmlns="' not in rendered
rendered = rendered.replace(' xmlns="', ' zulip-xmlns="')
parsed = etree.iterparse(StringIO(rendered))
for event, elem in parsed:
if 'zulip-xmlns' in elem.attrib:
elem.attrib['xmlns'] = elem.attrib.pop('zulip-xmlns')
root = elem
return root
else: # Something went wrong while rendering
span = Element('span')
span.set('class', 'tex-error')
span.text = '$$' + match.group('body') + '$$'
return span
示例7: zulip_specific_link_changes
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def zulip_specific_link_changes(self, el: Element) -> Union[None, Element]:
href = el.get('href')
# Sanitize url or don't parse link. See linkify_tests in markdown_test_cases for banned syntax.
href = sanitize_url(self.unescape(href.strip()))
if href is None:
return None # no-op; the link is not processed.
# Rewrite local links to be relative
db_data = self.md.zulip_db_data
href = rewrite_local_links_to_relative(db_data, href)
# Make changes to <a> tag attributes
el.set("href", href)
# Show link href if title is empty
if not el.text.strip():
el.text = href
# Prevent realm_filters from running on the content of a Markdown link, breaking up the link.
# This is a monkey-patch, but it might be worth sending a version of this change upstream.
el.text = markdown.util.AtomicString(el.text)
return el
示例8: generate_content_blocks
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def generate_content_blocks(self, tab_section: Dict[str, Any], lines: List[str]) -> str:
tab_content_blocks = []
for index, tab in enumerate(tab_section['tabs']):
start_index = tab['start'] + 1
try:
# If there are more tabs, we can use the starting index
# of the next tab as the ending index of the previous one
end_index = tab_section['tabs'][index + 1]['start']
except IndexError:
# Otherwise, just use the end of the entire section
end_index = tab_section['end_tabs_index']
content = '\n'.join(lines[start_index:end_index]).strip()
tab_content_block = DIV_TAB_CONTENT_TEMPLATE.format(
data_language=tab['tab_name'],
# Wrapping the content in two newlines is necessary here.
# If we don't do this, the inner Markdown does not get
# rendered properly.
content=f'\n{content}\n')
tab_content_blocks.append(tab_content_block)
return '\n'.join(tab_content_blocks)
示例9: atomic_brute_cast
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def atomic_brute_cast(tree: Element) -> Element:
"""
Cast every node's text into an atomic string to prevent further processing on it.
Since we generate the final HTML with Jinja templates, we do not want other inline or tree processors
to keep modifying the data, so this function is used to mark the complete tree as "do not touch".
Reference: issue [Python-Markdown/markdown#920](https://github.com/Python-Markdown/markdown/issues/920).
On a side note: isn't `atomic_brute_cast` such a beautiful function name?
Arguments:
tree: An XML node, used like the root of an XML tree.
Returns:
The same node, recursively modified by side-effect. You can skip re-assigning the return value.
"""
if tree.text:
tree.text = AtomicString(tree.text)
for child in tree:
atomic_brute_cast(child)
return tree
示例10: update_env
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def update_env(self, md: Markdown, config: dict) -> None:
"""
Update the Jinja environment.
Arguments:
md: The Markdown instance. Useful to add functions able to convert Markdown into the environment filters.
config: Configuration options for `mkdocs` and `mkdocstrings`, read from `mkdocs.yml`. See the source code
of [mkdocstrings.plugin.MkdocstringsPlugin.on_config][] to see what's in this dictionary.
"""
# Re-instantiate md: see https://github.com/tomchristie/mkautodoc/issues/14
md = Markdown(extensions=config["mdx"], extensions_configs=config["mdx_configs"])
def convert_markdown(text):
return do_mark_safe(md.convert(text))
self.env.filters["convert_markdown"] = convert_markdown
示例11: path_to_url
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def path_to_url(self, url):
scheme, netloc, path, params, query, fragment = urlparse(url)
if (scheme or netloc or not path or url.startswith('/') or url.startswith('\\')
or AMP_SUBSTITUTE in url or '.' not in os.path.split(path)[-1]):
# Ignore URLs unless they are a relative link to a source file.
# AMP_SUBSTITUTE is used internally by Markdown only for email.
# No '.' in the last part of a path indicates path does not point to a file.
return url
# Determine the filepath of the target.
target_path = os.path.join(os.path.dirname(self.file.src_path), urlunquote(path))
target_path = os.path.normpath(target_path).lstrip(os.sep)
# Validate that the target exists in files collection.
if target_path not in self.files:
log.warning(
"Documentation file '{}' contains a link to '{}' which is not found "
"in the documentation files.".format(self.file.src_path, target_path)
)
return url
target_file = self.files.get_file_from_path(target_path)
path = target_file.url_relative_to(self.file)
components = (scheme, netloc, path, params, query, fragment)
return urlunparse(components)
示例12: get_object
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def get_object(self):
obj = super(DetailView, self).get_object()
# 設置瀏覽量增加時間判斷,同一篇文章兩次瀏覽超過半小時才重新統計閱覽量,作者瀏覽忽略
u = self.request.user
ses = self.request.session
the_key = 'is_read_{}'.format(obj.id)
is_read_time = ses.get(the_key)
if u != obj.author:
if not is_read_time:
obj.update_views()
ses[the_key] = time.time()
else:
now_time = time.time()
t = now_time - is_read_time
if t > 60 * 30:
obj.update_views()
ses[the_key] = time.time()
md = markdown.Markdown(extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',
TocExtension(slugify=slugify),
])
obj.body = md.convert(obj.body)
obj.toc = md.toc
return obj
示例13: build_nav_menu
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def build_nav_menu(meta_cache):
""" Given a cache of Markdown `Meta` data, compile a structure that can be
used to generate the NAV menu.
This uses the `nav: Assembly>Bench>Part` variable at the top of the Markdown file.
"""
root = NavItem('root', 0)
# Pre-sort the nav-items alphabetically by nav-string. This will get overridden with the arange()
# function, but this avoids-un arranged items moving round between page refreshes due to Dicts being
# unordered.
sorted_meta_cache = sorted(
meta_cache.items(),
key = lambda items: items[1].get('nav', [''])[0].split('>')[-1] # Sort by the last part of the nav string for each page.
)
for path, meta in sorted_meta_cache:
nav_str = meta.get('nav', [None])[0]
nav_chunks = parse_nav_string(nav_str)
node = root
for name, weight in nav_chunks:
n = NavItem(name, weight)
node = node.add(n)
node.bind(meta=meta, link=path)
root.arrange()
return root
示例14: test_arg_source
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def test_arg_source(self):
"""
Test for the correct parsing of the source argument
"""
include_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
self.md = markdown.Markdown(extensions=['markdown.extensions.fenced_code',
'pymdownx.snippets', 'plantuml_markdown'],
extension_configs={
'plantuml_markdown': {
'base_dir': include_path
}
})
text = self.text_builder.diagram("ignored text").source("included_diag.puml").build()
self.assertEqual(self._stripImageData(self._load_file('include_output.html')),
self._stripImageData(self.md.convert(text)))
示例15: test_yaml_extension
# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import Markdown [as 別名]
def test_yaml_extension(self):
md = Markdown(
extensions=[MarkdownYamlMetaExtension()]
)
html = md.convert(TEST_VALID_CONTENT1)
self.assertEqual("<p>This is where the <strong>Markdown</strong> content will go.</p>", html.strip())
expected_meta = {
'some-variable': 'Value',
'other-variable': 'Another value',
'yet-another': ['this', 'is', 'a', 'list']
}
self.assertEqual(expected_meta, md.meta)
html = md.convert(TEST_VALID_CONTENT2)
self.assertEqual("<p>This is just some plain old <strong>Markdown</strong> content, without metadata.</p>", html.strip())
# no metadata
self.assertEqual({}, md.meta)