本文整理汇总了Python中markdown.Markdown.reset方法的典型用法代码示例。如果您正苦于以下问题:Python Markdown.reset方法的具体用法?Python Markdown.reset怎么用?Python Markdown.reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类markdown.Markdown
的用法示例。
在下文中一共展示了Markdown.reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
class Markdown:
def __init__(self):
self.markdown = MarkdownParser(
output_format='html5',
extensions = ['tables'],
)
def parse(self, fp):
meta = {}
def read_file():
in_head = True
for line in fp:
if not in_head:
yield line
else:
if len(line) < 2:
in_head = False
yield line
else:
name, value = line.split(':')
meta[name.lower()] = value.strip()
content = self.markdown.convert(''.join(read_file()))
self.markdown.reset()
pagetype = meta.pop('type', 'templated') # Default Pagetype
return pagetype, meta, content
示例2: load_blog
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def load_blog(blog_stuff):
meta = {
"title": (True, ("one",)),
"author": (True, ("one",)),
"date": (True, ("one", "iso-date")),
"photo": (False, ("one",)),
"photo_caption": (False, ("")),
}
markdowner = Markdown(extensions=["meta"], output_format="html5")
posts = []
for blog_file, filename in blog_stuff:
post = {}
html = markdowner.convert(blog_file.read()) # also loads metadata
post["content"] = Markup(html)
post["summary"] = Markup("\n".join(html.split("\n", 1)[:-1]))
post["slug"] = os.path.splitext(filename)[0]
for field, (required, filters) in meta.items():
field_val = markdowner.Meta.get(field)
try:
val = apply_field_constraints(field_val, required, filters)
except MetaError as e:
e.apply_context(filename, field)
raise e
post[field] = val
posts.append(post)
markdowner.reset()
return posts
示例3: load_blog
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def load_blog(blog_stuff):
meta = {
'title': (True, ('one',)),
'author': (True, ('one',)),
'date': (True, ('one', 'iso-date')),
'photo': (False, ('one',)),
'photo_caption': (False, (''))
}
markdowner = Markdown(extensions=['meta'], output_format='html5')
posts = []
for blog_file, filename in blog_stuff:
post = {}
html = markdowner.convert(blog_file.read()) # also loads metadata
post['content'] = Markup(html)
post['summary'] = Markup('\n'.join(html.split('\n', 1)[:-1]))
post['slug'] = os.path.splitext(filename)[0]
for field, (required, filters) in meta.items():
field_val = markdowner.Meta.get(field)
try:
val = apply_field_constraints(field_val, required, filters)
except MetaError as e:
e.apply_context(filename, field)
raise e
post[field] = val
posts.append(post)
markdowner.reset()
return posts
示例4: MarkdownReader
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [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
示例5: load_stories
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def load_stories(story_stuff):
meta = {
'title': (True, ('one',)),
'description': (True, ('one',)),
}
markdowner = Markdown(extensions=['meta'], output_format='html5')
stories = []
for story_file, filename in story_stuff:
story = {}
html = markdowner.convert(story_file.read()) # also loads metadata
story['body'] = Markup(html)
story['slug'] = os.path.splitext(filename)[0]
for field, (required, filters) in meta.items():
field_val = markdowner.Meta.get(field)
try:
val = apply_field_constraints(field_val, required, filters)
except MetaError as e:
e.apply_context(filename, field)
raise e
story[field] = val
stories.append(story)
markdowner.reset()
return stories
示例6: load_stories
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def load_stories(story_stuff):
meta = {
"title": (True, ("one",)),
"description": (True, ("one",)),
"image": (True, ("one",)),
"button": (True, ("one",)),
"link": (True, ("one",)),
"button2": (False, ("one",)),
"link2": (False, ("one",)),
"action": (False, ("one",)),
}
markdowner = Markdown(extensions=["meta"], output_format="html5")
stories = []
for story_file, filename in story_stuff:
story = {}
html = markdowner.convert(story_file.read()) # also loads metadata
story["body"] = Markup(html)
story["slug"] = os.path.splitext(filename)[0]
for field, (required, filters) in meta.items():
field_val = markdowner.Meta.get(field)
try:
val = apply_field_constraints(field_val, required, filters)
except MetaError as e:
e.apply_context(filename, field)
raise e
story[field] = val
stories.append(story)
markdowner.reset()
return stories
示例7: markdown
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def markdown(self, input_path, extensions=None):
exts = ['abbr','fenced_code','footnotes','tables','codehilite','smarty','toc', 'attr_list','def_list'] if extensions==None else extensions
style = ",".join(self.__sheets)
styleext = MdStyle(configs={"sheets":[style, "The stylesheet list"]})
exts += [styleext]
md = Markdown(extensions=exts, output_format="html5")
md.stripTopLevelTags = False
md.reset().convertFile(input=input_path, output=input_path + ".html")
示例8: parse_files
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def parse_files():
md = Markdown(extensions=["markdown.extensions.meta"])
files = []
for f in get_content_files():
io = StringIO()
md.reset().convertFile(f, output=io)
mt = parse_meta_info(md.Meta)
files.append((mt, io.getvalue().decode("utf8")))
del io
return files
示例9: MarkdownConverter
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
class MarkdownConverter(Converter):
"""
Converts Markdown files into HTML using templates specified in the header.
"""
def __init__(self, site_path, path):
self.path = path
self.full_path = os.path.join(site_path, path)
base, ext = os.path.splitext(self.path)
self.target_path = base + ".html"
self.full_target_path = os.path.join(site_path, self.target_path)
self._md = Markdown(extensions=['meta', 'extra'])
templates_dir = os.path.join(site_path, TEMPLATES_DIR)
self._env = jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir))
@staticmethod
def matches(path):
return path.endswith(".md") or path.endswith(".markdown")
def target(self):
return self.target_path
def dependencies(self):
return [] # Not implemented
def _convert_markdown(self, text):
html = self._md.convert(text)
context = {'content': html}
if hasattr(self._md, 'Meta'):
for key, value in self._md.Meta.items():
context[key] = "\n".join(value)
self._md.reset()
return context
def convert(self):
with open(self.full_path) as f:
text = f.read()
context = self._convert_markdown(text)
template_name = context.get("template", "default") + ".html"
try:
template = self._env.get_template(template_name)
full_html = template.render(context)
with open(self.full_target_path, "w") as f:
f.write(full_html)
except jinja2.TemplateNotFound as e:
return ErrorMessage(self.path, "Template '%s' was not found" % (e.name,))
except jinja2.TemplateSyntaxError as e:
return ErrorMessage(os.path.join(TEMPLATES_DIR, e.name),
"Template syntax error: %s" % (e.message,))
示例10: MDProgram
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
class MDProgram(TemplatedProgram):
"""A program that renders an rst file into a template"""
default_template = 'md_display.html'
def __init__(self, context):
from markdown import Markdown
self.md = Markdown(
output_format = 'html5',
safe_mode = 'escape',
enable_attributes = True,
extensions = [
'smart_strong',
'fenced_code',
'footnotes',
'attr_list',
'def_list',
'tables',
'abbr',
'meta',
'headerid',
'codehilite(pygments_style=tango, css_class=syntax, guess_lang=True)'
]
)
self.contents = {}
TemplatedProgram.__init__(self, context)
def prepare(self):
with self.context.open_source_file() as f:
parsed = self.md.convert(f.read())
self.context.config = self.context.config.add_from_dict(self.md.Meta)
self.contents['fragment'] = parsed
self.contents['html_title'] = self.contents['title'] = self.context.title = u' '.join(self.md.Meta.get('title', u''))
self.contents['summary'] = self.context.summary = u' '.join(self.md.Meta.get('summary', u''))
def render(self, contents):
self.md.reset()
return self.md.convert(contents)
def render_contents(self):
return self.contents['fragment']
def get_template_context(self):
ctx = TemplatedProgram.get_template_context(self)
ctx['md'] = self.contents
return ctx
示例11: markdown_read
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def markdown_read(self, source_path):
md = Markdown(extensions=self.extensions)
with pelican_open(source_path) as text:
content = md.convert(text)
metadata = {}
for name, value in md.Meta.items():
name = name.lower()
if name == "summary":
summary_values = "\n".join(value)
md.reset()
summary = md.convert(summary_values)
metadata[name] = self.process_metadata(name, summary)
elif len(value) > 1:
metadata[name] = self.process_metadata(name, value)
else:
metadata[name] = self.process_metadata(name, value[0])
return content, metadata
示例12: ThreadLocalMarkdown
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
class ThreadLocalMarkdown(threading.local):
"""Convert Markdown to HTML using per-thread Markdown objects.
See discussion in #2661.
"""
def __init__(self, extensions, extension_configs):
"""Create a Markdown instance."""
self.markdown = Markdown(extensions=extensions, extension_configs=extension_configs, output_format="html5")
def convert(self, data):
"""Convert data to HTML and reset internal state."""
result = self.markdown.convert(data)
try:
meta = {}
for k in self.markdown.Meta: # This reads everything as lists
meta[k.lower()] = ','.join(self.markdown.Meta[k])
except Exception:
meta = {}
self.markdown.reset()
return result, meta
示例13: convert_source
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def convert_source(self):
'''
Convert all Markdown pages to HTML and metadata pairs. Returns a list of
all the content pairs, sorted by date.
'''
md = Markdown(extensions=self.config.markdown_extensions, output_format='html5')
converted_docs = []
for root, dirs, file_names in walk(self.config.site.content.source):
for file_name in file_names:
file_path = path.join(root, file_name)
plain_slug, extension = path.splitext(file_name)
with open(file_path, 'r') as file:
md_document = file.read()
html_document = md.convert(md_document)
converted_doc = Content_Pair(html_document, md.Meta)
self.__normalize_meta(converted_doc.meta, plain_slug)
converted_docs.append(converted_doc)
md.reset()
converted_docs = [doc for doc in converted_docs if not doc.meta['ignore']]
converted_docs.sort(key=lambda post: post.meta['sort_date'], reverse=True)
return converted_docs
示例14: read_markdown
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
def read_markdown(filename):
"""Reads markdown file, converts output and fetches title and meta-data for
further processing.
"""
global MD
# Use utf-8-sig codec to remove BOM if it is present. This is only possible
# this way prior to feeding the text to the markdown parser (which would
# also default to pure utf-8)
with open(filename, 'r', encoding='utf-8-sig') as f:
text = f.read()
if MD is None:
MD = Markdown(extensions=['markdown.extensions.meta',
'markdown.extensions.tables'],
output_format='html5')
else:
MD.reset()
# When https://github.com/Python-Markdown/markdown/pull/672
# will be available, this can be removed.
MD.Meta = {}
# Mark HTML with Markup to prevent jinja2 autoescaping
output = {'description': Markup(MD.convert(text))}
try:
meta = MD.Meta.copy()
except AttributeError:
pass
else:
output['meta'] = meta
try:
output['title'] = MD.Meta['title'][0]
except KeyError:
pass
return output
示例15: MdView
# 需要导入模块: from markdown import Markdown [as 别名]
# 或者: from markdown.Markdown import reset [as 别名]
#.........这里部分代码省略.........
def load_files (self, *files) :
if files :
files = list(map(os.path.abspath, files))
if self.file in files :
self.menu.set_view_source(False)
self.zoom_100()
self.reload()
files.remove(self.file)
else :
while files :
if self.load(files.pop(0)) : break
if files :
files.insert(0, __file__)
if sys.executable : files.insert(0, sys.executable)
Popen(files)
def load (self, file, lock_scrolling = False) :
old_file, self.file = self.file, os.path.abspath(file)
old_html, self.html = self.html, None
if self.reload(lock_scrolling) :
self._setup_monitor()
self.zoom_100()
self.menu.set_document_available(True)
self.menu.set_view_source(False)
self.set_title("{2} ({1}) - {0}".format(__appname__, *os.path.split(self.file.replace(self.USER_HOME, '~', 1))))
return old_file or True
self.file = old_file
self.html = old_html
def reload (self, lock_scrolling = False) :
try :
if self.file :
with open(self.file, 'r', 'utf-8') as f : self.html = self.md.reset().convert(f.read())
self._load_html(lock_scrolling)
return True
except : self._show_error_dialog(_("Failed loading file {0}").format(self.file))
def export_html (self, file) :
try :
if file :
with open(file, 'w', 'utf-8') as f : f.write(self.html)
return True
except : self._show_error_dialog(_("Failed writing file {0}").format(self.file))
def toggle_view_source (self) : self.menu.set_view_source(not self.webview.get_view_source_mode())
def zoom_100 (self, *args) : self.webview.set_zoom_level(1)
def on_file_changed (self, monitor, file, new_file, event) :
if event == Gio.FileMonitorEvent.CHANGES_DONE_HINT :
self.reload(True)
elif event == Gio.FileMonitorEvent.CREATED :
self._setup_monitor()
self.reload(True)
elif event == Gio.FileMonitorEvent.MOVED :
self.load(new_file.get_path(), True)
def on_drag_data_received (self, widget, drag_context, x, y, data, info, time) :
self.load_files(*map(lambda uri : unquote(urlparse(uri).path), data.get_uris()))
def on_hovering_over_link (self, webview, title, uri) :
if uri :
self.uri_label.set_text(uri)
self.uri_label.show()
else :