Python mistune 模块,Markdown() 实例源码

我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用mistune.Markdown()

项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def article_detail_handler(request, article_id):
    account = request.META["user_info"]
    result = dict()

    renderer = mistune.Renderer(hard_wrap=True, parse_inline_html=True)
    markdown = mistune.Markdown(renderer=renderer)

    article = BlogArticle.query_article_by_id(article_id)
    article["content"] = markdown(article["content"])
    article["comment_list"] = BlogComment.query_comment_list(article_id, account.id if account else 0)
    result["article"] = article

    if account:
        article["meta_info"]["liked"] = 1 if BlogLike.query_like_blog(account.id, article_id) else 0
        result["user_info"] = UserInfo.query_format_info_by_user_id(request.META["user_info"].id)

    # ?????? ????????????????????
    author_id = article["user_info"]["id"]
    if not account or author_id != account.id:
        BlogArticleMeta.change_meta_record(article_id, author_id, ["hit"])
        # ????
        BlogArticle.query_article_by_id(article_id, False)

    return render(request, "article/detail.html", result)
项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def edit_article_handler(request, article_id):
    """
    ???? ????
    """
    result = base_result()
    user_id = request.META["user_info"].id

    if article_id != "0":
        result["data"] = BlogArticle.query_article_by_id(article_id)

        renderer = mistune.Renderer(hard_wrap=True, parse_inline_html=True)
        markdown = mistune.Markdown(renderer=renderer)

        result["mark_down"] = markdown(result["data"]["content"])
    else:
        result["mark_down"] = None
        del result["data"]

    result["kind_list"] = BlogKind.query_user_kind(1)
    result["user_info"] = UserInfo.query_format_info_by_user_id(user_id)

    return render(request, "manage/edit.html", result)
项目:slidoc    作者:mitotic    | 项目源码 | 文件源码
def extract_slide_range(src_path, web_path, start_slide=0, end_slide=0, renumber=0, session_name=''):
    # Extract text and images for a range of slides from Markdown file
    # Return (md_defaults, slides_text_md, slides_images_zip or None, new_image_number)
    md_defaults, md_slides, new_image_number = extract_slides(src_path, web_path)

    if not start_slide:
        start_slide = 1
    elif start_slide > len(md_slides):
        raise Exception('Invalid slide number %d' % start_slide)

    if not end_slide:
        end_slide = len(md_slides)

    fname = os.path.splitext(os.path.basename(src_path))[0]
    if not session_name:
        session_name = fname
    md_extract = ''.join(md_slides[start_slide-1:end_slide])
    extract_mods_args = md2md.Args_obj.create_args(None,
                                                  image_dir=session_name+'_images',
                                                  images=set(['_slidoc', 'zip', 'md']),
                                                  renumber=renumber)
    extract_parser = md2md.Parser(extract_mods_args)
    extract_text, extract_zipped, tem_image_number = extract_parser.parse(md_extract, src_path)

    return (md_defaults, extract_text, extract_zipped, tem_image_number if renumber else new_image_number)
项目:yafblog    作者:jifegg    | 项目源码 | 文件源码
def save(self):
        article_info = Article.findOne('title=?', [self.title])
        if article_info:
            return {'code':-1, 'msg':'????????'}
        self.archive = time.strftime('%Y%m')
        self.addtime = int(time.time())
        my_render = MyRenderer()
        my_render.reset_toc()
        markdown = mistune.Markdown(renderer=my_render)
        self.content_html = markdown(self.content)
        self.toc_html = my_render.render_toc(level=3)

        # category
        Category.inc_num(self.category)

        # tag
        for tag_id in self.tags:
            Tag.inc_num(tag_id)
        if self.tags:
            self.tags = ','.join(self.tags)

        # archive
        archive = str(time.strftime('%Y%m'))
        Archive.inc_num(archive)
        return super().save()
项目:cb-swagger    作者:couchbaselabs    | 项目源码 | 文件源码
def parse(self, text, complete_page=True, page_id='enter-id-here',
              title='Enter the page title here'):
        output = super(Markdown, self).parse(text)

        if output.startswith('</section>'):
            output = output[9:]
        elif complete_page:
            output = '<section>\n' + output

        if complete_page:
            output = """<?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE concept PUBLIC "-//OASIS//DTD DITA Concept//EN" "concept.dtd">
    <concept xml:lang="en-us" id="{0}">
    <title>{1}</title>
    <shortdesc>Enter the short description for this page here</shortdesc>
    <conbody>
    {2}</section>
    </conbody>
    </concept>""".format(page_id, title, output)
        return output
项目:cb-swagger    作者:couchbaselabs    | 项目源码 | 文件源码
def main():
    parsed_args = _parse_args(sys.argv[1:])

    if parsed_args.input_file:
        input_str = open(parsed_args.input_file, 'r').read()
    elif not sys.stdin.isatty():
        input_str = ''.join(line for line in sys.stdin)
    else:
        print('No input file specified and unable to read input on stdin.\n'
              "Use the '-h' or '--help' flag to see usage information",
              file=sys.stderr)
        exit(1)

    markdown = Markdown()
    dita_output = markdown(input_str)

    if parsed_args.output_file:
        with open(parsed_args.output_file, 'w') as output_file:
            output_file.write(dita_output)
    else:
        print(dita_output)
项目:CustomContextMenu    作者:bigsinger    | 项目源码 | 文件源码
def block_code(self, code, lang):
        lang = CODE_LANG
        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % \
                mistune.escape(code)
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter()
        return highlight(code, lexer, formatter)

# renderer = HighlightRenderer()
# markdown = mistune.Markdown(renderer=renderer)
# print(markdown('```python\nassert 1 == 1\n```'))
项目:CustomContextMenu    作者:bigsinger    | 项目源码 | 文件源码
def convert_md_file(argv):
    is_convert_html = True
    if len(sys.argv) >= 3:
        is_convert_html = False

    md_filename = argv[0]
    css_filename = os.path.join(getthispath(), 'default.css')   # ??CSS????http://richleland.github.io/pygments-css/
    html_filename = '%s.html' % (md_filename[:-3])
    pdf_filename = '.'.join([md_filename.rsplit('.')[0], 'pdf'])
    css_text = None
    md_text = None

    with codecs.open(css_filename, mode='r', encoding='utf-8') as f:
        css_text = '<style type = "text/css">\n' + f.read() + "\n</style>\n"

    with codecs.open(md_filename, mode='r', encoding='utf-8') as f:
        md_text = f.read()

    # ?????????mistune
    if False:
        html_text = md2html_by_markdown2(md_text)
    else:
        global CODE_LANG
        CODE_LANG = 'java'
        markdown = mistune.Markdown(renderer=HighlightRenderer())
        html_text = markdown(md_text)

    if is_convert_html:
        # save to html file
        #?windows?encoding?????gbk??????utf-8???????
        with codecs.open(html_filename, 'w', encoding='gbk', errors='xmlcharrefreplace') as f:
            f.write(css_text + html_text)
        if os.path.exists(html_filename):
            os.popen(html_filename)
    else:
        # save to pdf file
        HTML(string=html_text).write_pdf(pdf_filename, stylesheets=[css_filename])
        if os.path.exists(pdf_filename):
            os.popen(pdf_filename)
项目:pony    作者:Eastwu5788    | 项目源码 | 文件源码
def markdown_engin(ori_str=""):
    renderer = mistune.Renderer(hard_wrap=True, parse_inline_html=True)
    markdown = mistune.Markdown(renderer=renderer)
    return markdown(ori_str)
项目:slidoc    作者:mitotic    | 项目源码 | 文件源码
def extract_slides(src_path, web_path):
    # Extract text for individual slides from Markdown file
    # Return (md_defaults, md_slides, new_image_number)
    try:
        with open(src_path) as f:
            source = f.read()
    except Exception, excp:
        raise Exception('Error in reading module source text %s: %s' % (src_path, excp))

    try:
        with open(web_path) as f:
            sessionIndex = read_index(f, path=web_path)
            sessionIndexParams = sessionIndex[0][-1]
    except Exception, excp:
        raise Exception('Error in reading module published HTML %s: %s' % (web_path, excp))

    md_source = preprocess(source).strip()
    if sliauth.digest_hex(md_source) != sessionIndexParams['md_digest']:
        raise Exception('Digest mismatch src=%s vs. web=%s; may need to re-publish HTML file %s by previewing all slides and saving' % (sliauth.digest_hex(md_source), sessionIndexParams['md_digest'], web_path))
    md_slides = []

    base = len(sessionIndexParams['md_defaults'])
    offset = 0
    for count in sessionIndexParams['md_breaks']:
        md_slides.append(md_source[base+offset:base+count])
        offset = count
    return (sessionIndexParams['md_defaults'], md_slides, sessionIndexParams['new_image_number'])
项目:mkaestatic    作者:michibo    | 项目源码 | 文件源码
def get_markdown_renderer( url_transform ):
    ''' This function returns a markdown renderer which transforms 
        URLs according to the relative paradigm of mkaestatic.
    '''

    class MyRenderer( mistune.Renderer ):
        def link(self, link, title, text):
            link = url_transform(link)
            return super(MyRenderer, self).link(link, title, text)

        def image(self, src, title, alt_text):
            src = url_transform(src)
            return super(MyRenderer, self).image(src, title, alt_text)

    return mistune.Markdown(renderer=MyRenderer(escape=True, use_xhtml=True))
项目:FBlog-python3-webapp    作者:fuyangzhen    | 项目源码 | 文件源码
def markdown_highlight(content):
    markdown = mistune.Markdown(renderer=HighlightRenderer(), hard_wrap=True)
    return markdown(content)
项目:dystic    作者:oxalorg    | 项目源码 | 文件源码
def __init__(self):
        self.renderer = HighlightRenderer()
        self.markdown = mistune.Markdown(renderer=self.renderer)
项目:DjangoBlog    作者:liangliangyy    | 项目源码 | 文件源码
def get_markdown(value):
        renderer = BlogMarkDownRenderer(inlinestyles=False)

        mdp = mistune.Markdown(escape=True, renderer=renderer)
        return mdp(value)
项目:yafblog    作者:jifegg    | 项目源码 | 文件源码
def update(self, old):
        if self.title != old['title']:
            article_info = Article.findOne('title=?', [self.title])
            if article_info:
                return {'code':-1, 'msg':'????????'}
        my_render = MyRenderer()
        my_render.reset_toc()
        markdown = mistune.Markdown(renderer=my_render)
        self.content_html = markdown(self.content)
        self.toc_html = my_render.render_toc(level=3)

        # category
        if (self.category != old['category']):
            Category.dec_num(old['category'])
            Category.inc_num(self.category)

        # tag
        old['tags'] = old['tags'].split(',');
        for tag_id in set(old['tags']) - set(self.tags):
            if tag_id:
                Tag.dec_num(tag_id)
        for tag_id in set(self.tags) - set(old['tags']):
            if tag_id:
                Tag.inc_num(tag_id)
        if self.tags:
            self.tags = ','.join(self.tags)
        else:
            self.tags = ''

        res = super().update()
        return res
项目:Odin    作者:HackSoftware    | 项目源码 | 文件源码
def convert_from_markdown(text):
    md = mistune.Markdown()
    return md(text)
项目:cb-swagger    作者:couchbaselabs    | 项目源码 | 文件源码
def __init__(self, renderer=None, inline=None, block=None, **kwargs):
        if not renderer:
            renderer = Renderer(**kwargs)
        else:
            kwargs.update(renderer.options)

        super(Markdown, self).__init__(
            renderer=renderer, inline=inline, block=block)
项目:cb-swagger    作者:couchbaselabs    | 项目源码 | 文件源码
def markdown(text, escape=True, **kwargs):
    return Markdown(escape=escape, **kwargs)(text)
项目:blog-django    作者:delitamakanda    | 项目源码 | 文件源码
def markdown(value):
    renderer = HightLightRenderer()
    markdown = mistune.Markdown(renderer=renderer)
    return markdown(value)
项目:headcache    作者:s9w    | 项目源码 | 文件源码
def __init__(self, parent):
        super().__init__(parent)

        with open(pkg_resources.resource_filename("headcache", 'preview_style.css')) as file_style:
            self.preview_css_str = '<style type="text/css">{}</style>'.format(file_style.read())

        # markdown
        self.ast_generator = AstBlockParser()
        self.markdowner_simple = mistune.Markdown(renderer=IdRenderer())

        # stored data
        self.data = self.load_data()
        self.usage_mode = "browse"
        self.initUI()

        self.config = self.load_config()

        # setup search index
        analyzer_typing = StandardAnalyzer() | NgramFilter(minsize=2, maxsize=8)
        schema = Schema(
            title=TEXT(stored=True, analyzer=analyzer_typing, field_boost=self.config["search_title_weight"]),
            content=TEXT(stored=True, analyzer=analyzer_typing, field_boost=self.config["search_text_weight"]),
            time=STORED,
            path=ID(stored=True),
            tags=KEYWORD)
        if not os.path.exists("indexdir"):
            os.mkdir("indexdir")
        self.ix = create_in("indexdir", schema)

        # setup GUI

        self.old_sizes = self.splitter.sizes()
        self.parent().resize(*self.config["window_size"])

        if self.data:
            self.list1.setCurrentRow(0)
            self.list1.setFocus()

        self.overlay = Overlay(self)
        self.overlay.hide()
        self.setObjectName("mainframe")

        self.setFocusPolicy(Qt.StrongFocus)

        self.fileWatcher = watchdog.observers.Observer()
        watcher = FileChangeWatcher()
        self.fileWatcher.schedule(watcher, path=os.getcwd(), recursive=False)
        watcher.signal_deleted.connect(self.file_deleted)
        watcher.signal_modified.connect(self.file_modified)
        watcher.signal_added.connect(self.file_added)
        self.fileWatcher.start()