当前位置: 首页>>代码示例>>Python>>正文


Python markdown.Markdown方法代码示例

本文整理汇总了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 
开发者ID:greenape,项目名称:mknotebooks,代码行数:21,代码来源:plugin.py

示例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 
开发者ID:zmrenwu,项目名称:django-mptt-comments,代码行数:26,代码来源:models.py

示例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) 
开发者ID:vmarkovtsev,项目名称:plueprint,代码行数:27,代码来源:__main__.py

示例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) 
开发者ID:vmarkovtsev,项目名称:plueprint,代码行数:27,代码来源:test.py

示例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) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:21,代码来源:__main__.py

示例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 
开发者ID:zulip,项目名称:zulip,代码行数:22,代码来源:__init__.py

示例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 
开发者ID:zulip,项目名称:zulip,代码行数:26,代码来源:__init__.py

示例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) 
开发者ID:zulip,项目名称:zulip,代码行数:23,代码来源:tabbed_sections.py

示例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 
开发者ID:pawamoy,项目名称:mkdocstrings,代码行数:24,代码来源:extension.py

示例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 
开发者ID:pawamoy,项目名称:mkdocstrings,代码行数:18,代码来源:__init__.py

示例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) 
开发者ID:mkdocs,项目名称:mkdocs,代码行数:27,代码来源:pages.py

示例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 
开发者ID:stormsha,项目名称:blog,代码行数:27,代码来源:views.py

示例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 
开发者ID:HEInventions,项目名称:docnado,代码行数:27,代码来源:docnado.py

示例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))) 
开发者ID:mikitex70,项目名称:plantuml-markdown,代码行数:18,代码来源:test_plantuml.py

示例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) 
开发者ID:thanethomson,项目名称:statik,代码行数:19,代码来源:test_markdown_exts.py


注:本文中的markdown.Markdown方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。