本文整理汇总了Python中CommonMark.commonmark方法的典型用法代码示例。如果您正苦于以下问题:Python CommonMark.commonmark方法的具体用法?Python CommonMark.commonmark怎么用?Python CommonMark.commonmark使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CommonMark
的用法示例。
在下文中一共展示了CommonMark.commonmark方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: markdown
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def markdown(md, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
html = CommonMark.commonmark(esc(md))
return mark_safe(html)
示例2: generate_email
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def generate_email(self, data, tagline):
email = u"""
Hi {name},
{tagline}
## Outgoing Calls
{outgoing}
## Incoming Calls
{incoming}
Thanks,
The Call Stats Robot
""".format(
name=data['name'],
outgoing=self.stats_markdown(data['outgoing']),
incoming=self.stats_markdown(data['incoming']),
tagline=tagline)
html_email = CommonMark.commonmark(email)
# Send HTML email
html_part = MIMEText(html_email, 'html', 'utf-8')
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Your Call Stats'
msg['From'] = local_settings.SMTP_FROM
msg['To'] = data['email']
msg.attach(html_part)
self.smtp.sendmail(
local_settings.SMTP_FROM,
data['email'], msg.as_string())
示例3: toHTML
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def toHTML(self,md,metadata,html,generateTitle=False):
uri = self.weburi + metadata['published'][0]
print('<article xmlns="http://www.w3.org/1999/xhtml" vocab="{}" typeof="{}" resource="{}">'.format(self.vocab,self.typeof,uri),file=html)
print('<script type="application/json+ld">',file=html)
print('{\n"@context" : "http://schema.org/",',file=html)
print('"@id" : "{}",'.format(uri),file=html)
print('"headline" : "{}",'.format(metadata['title'][0]),file=html)
print('"datePublished" : "{}",'.format(metadata['published'][0]),file=html)
print('"dateModified" : "{}",'.format(metadata['updated'][0]),file=html)
if ("keywords" in metadata):
print('"keywords" : [{}],'.format(','.join(['"' + m + '"' for m in metadata['keywords']])),file=html)
html.write('"author" : [ ')
for index,author in enumerate(metadata['author']):
if (index>0):
html.write(', ')
html.write('{{ "@type" : "Person", "name" : "{}" }}'.format(author))
html.write(']\n')
print('}',file=html)
print('</script>',file=html)
if generateTitle:
print("<h1>{}</h1>".format(escape(metadata['title'][0],quote=False)),file=html)
print(CommonMark.commonmark(md),file=html)
print('</article>',file=html)
示例4: get
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def get(self):
posts = glob("posts/*.md")
output = '<html><head><link rel="stylesheet" href="tufte.css"/></head><body>'
archive_content = "# Archive\n\nHere's an archive of all of my published posts:\n\n"
metadata = {}
ordered_posts = {}
if len(posts) > 0:
for post in posts:
metadata[post] = extract_metadata(post)
for post in posts:
print(metadata[post])
if metadata[post] is not None:
if 'post_number' in metadata[post].keys():
ordered_posts[metadata[post]['post_number']] = post[6:-3]
for i in range(1,len(ordered_posts.keys())+1):
post = ordered_posts[i]
archive_content += "1. [" + post + "](" + post + ")\n"
archive_content += "\n\n"
print(ordered_posts)
output += cm.commonmark(archive_content)
output += '</body></html>'
self.write(output)
示例5: read_wiki_page
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def read_wiki_page(path):
# Turn the URL-style path into the canonical filesystem-aware path
path = path.replace('/', os.path.sep).lower()
full_path = os.path.join(wiki_bp.root_path, wiki_bp.static_folder, path)
reg_path = _get_md(full_path)
dir_path = _get_md(os.path.join(full_path, '_index'))
if os.path.isfile(reg_path):
full_path = reg_path
elif os.path.isfile(dir_path):
full_path = dir_path
elif os.path.isdir(full_path):
files = os.listdir(full_path)
lines = ['<h1>{}</h1>'.format(fn2title(path) or 'Home')]
for f in files:
if f.startswith('.'):
continue
f = os.path.splitext(f)[0]
wiki_path = '/'.join([path, f]) if path else f
if os.path.isdir(os.path.join(full_path, f)):
wiki_path += '/'
lines.append('<a href="{}">{}</a>'.format(url_for('.wiki', wiki_path=wiki_path), fn2title(f)))
return '\n'.join(lines)
else:
abort(404)
with open(full_path) as fl:
return commonmark.commonmark(fl.read().decode('utf-8'))
示例6: test_unicode
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def test_unicode(self):
s = CommonMark.commonmark('<div>\u2020</div>\n')
self.assertEqual(s, '<div>\u2020</div>\n',
'Unicode works in an HTML block.')
CommonMark.commonmark('* unicode: \u2020')
CommonMark.commonmark('# unicode: \u2020')
CommonMark.commonmark('```\n# unicode: \u2020\n```')
示例7: create_post
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def create_post(request):
print request.FILES.get('file')
print type(request.FILES.get('file'))
image = request.FILES.get('file')
content = request.POST.get('post-input')
published = datetime.now()
is_markdown = json.loads(request.POST.get('is-markdown-post'))
if is_markdown:
contentType = "text/x-markdown"
content = CommonMark.commonmark(content)
else:
contentType = "text/plain"
visibility = request.POST.get('visibility')
c_username = request.user.username
user_object = User.objects.get(username=c_username)
author_object = Author.objects.get(email=user_object)
author_name = author_object.displayName
post_id = uuid.uuid4()
DITTO_HOST = 'http://' + request.get_host() + '/api/posts/' + str(post_id)
title = request.POST.get('title')
description = request.POST.get('description')
categories = request.POST.get('categories')
c = categories.split(' ')
categories_json = json.dumps(c)
new_post = Post(published=published, author=author_object, content=content, contentType=contentType,
visibility=visibility, source=DITTO_HOST, origin=DITTO_HOST, categories=categories, title=title,
description=description, id = post_id)
new_post.save()
if image:
print image.content_type
#image.name = str(uuid.uuid4())
print image.name
print "before creating"
new_image = Img(actual_image = image)
new_image.parent_post = new_post
print "before saving"
new_image.save()
print "after saving"
new_post.content = new_post.content + ' <br> <img src="http://ditto-test.herokuapp.com/ditto/media/images/'+image.name+'" >'
#new_post.content = new_post.content + ' <br> <img src="http://localhost:8000/ditto/media/images/'+image.name+'" >'
new_post.save()
return HttpResponse(request.POST.get('post_body'))
示例8: render
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def render(self, context):
text = self.nodelist.render(context)
if self.title:
text = "### %s\n\n%s" % (self.title, text)
#text = markdown(text)
text = CommonMark.commonmark(text)
link_anchor = ANCHOR_PATTERN % self.anchor
text = bleach.linkify(text, callbacks=self.CALLBACKS, skip_pre=True)
text = link_anchor + text + TOP_LINK
return text
示例9: render_markdown
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def render_markdown(content):
"""
Return a html fragment from markdown text content
Parameters
----------
content : str
A markdown formatted text
Returns
-------
html : str
"""
return CommonMark.commonmark(content)
示例10: get_thumbnail_url
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def get_thumbnail_url(doc, pagenumber, small):
# Returns a URL to a thumbnail image for a particular page of the document.
# 'small' is a boolean.
# If the document is on DocumentCloud, get the URL to DocumentCloud's thumbnail image.
documentcloud_id = get_documentcloud_document_id(doc)
if documentcloud_id:
# We can use the DocumentCloud API to get the URL to a thumbnail, but in the
# interests of speed, construct the URL ourselves.
#return query_documentcloud_api(documentcloud_id)["document"]["resources"]["page"]["image"].format(
# page=pagenumber,
# size="small" if small else "normal",
#)
return "https://assets.documentcloud.org/documents/%s/pages/%s-p%d-%s.gif" % (
documentcloud_id[0], documentcloud_id[1], pagenumber, "small" if small else "normal")
# If it's a Markdown document, download it, convert it to HTML, then render it to
# a PDF, and then to an image, and return that image as a data: URL.
elif doc.get("format") == "markdown" and os.path.exists("/usr/bin/htmldoc") and os.path.exists("/usr/bin/pdftoppm"):
# Download the Markdown file.
md = get_document_text(doc, pagenumber)
# If we got it...
if md:
import subprocess, base64
# Render the Markdown as HTML.
html = CommonMark.commonmark(md)
# Render the HTML as a PDF.
# TODO: Possible security issue if the Markdown source can generate HTML that
# causes htmldoc to perform network requests or possibly unsafe operations.
pdf = subprocess.check_output(["/usr/bin/htmldoc", "--quiet", "--continuous",
"--size", "4.5x5.8in", # smaller page magnifies the text
"--top", "0", "--right", "1cm", "--bottom", "1cm", "--left", "1cm", # margins
"-t", "pdf14", "-"],
input=html.encode("utf8"))
# Render the PDF and a PNG.
png = subprocess.check_output(["/usr/bin/pdftoppm", "-singlefile", "-r", "60", "-png"],
input=pdf)
# Return a data: URL so we don't have to store/host the image anywhere,
# but we can display it directly.
return "data:image/png;base64," + base64.b64encode(png).decode("ascii")
# No thumbnail image is available for this resource.
return None
示例11: report
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def report(env, node_name, report_id):
"""Displays a single report including all the events associated with that
report and their status.
The report_id may be the puppetdb's report hash or the
configuration_version. This allows for better integration
into puppet-hipchat.
:param env: Search for reports in this environment
:type env: :obj:`string`
:param node_name: Find the reports whose certname match this value
:type node_name: :obj:`string`
:param report_id: The hash or the configuration_version of the desired
report
:type report_id: :obj:`string`
"""
envs = environments()
check_env(env, envs)
query = AndOperator()
report_id_query = OrOperator()
report_id_query.add(EqualsOperator("hash", report_id))
report_id_query.add(EqualsOperator("configuration_version", report_id))
if env != '*':
query.add(EqualsOperator("environment", env))
query.add(EqualsOperator("certname", node_name))
query.add(report_id_query)
reports = puppetdb.reports(query=query)
try:
report = next(reports)
except StopIteration:
abort(404)
report.version = CommonMark.commonmark(report.version)
return render_template(
'report.html',
report=report,
events=yield_or_stop(report.events()),
logs=report.logs,
metrics=report.metrics,
envs=envs,
current_env=env)
示例12: generate_html
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def generate_html(self, mdfile=None):
if mdfile is None:
mdf = self.mdfile
else:
mdf = mdfile
filepath = "posts/" + mdf
if mdf[-3:] != ".md":
filepath += ".md"
with open(filepath) as open_md:
content = open_md.readlines()
header = []
markdown = self.__parse_yaml_frontmatter(content)
markdown = ''.join(markdown)
return self.preamble + cm.commonmark(markdown) + self.closing
示例13: post_new
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def post_new(request):
if request.method == "POST":
form = PostForm(data=request.POST)
#print("REQUEST.POST:%s"%request.POST)
imageForm = ImageForm(request.POST, request.FILES)
#print("FILES: %s"%request.FILES['imageFile'])
#print(form)
#print(form.errors)
if form.is_valid():
post = form.save(commit=False)
post.author = Author.objects.get(user=request.user.id)
post.published = timezone.now()
if post.contentType == 'text/x-markdown':
post.content = CommonMark.commonmark(post.content)
post.set_source()
post.set_origin()
post.save()
if request.POST['image_url']:
post.content = post.content + "<br><img src="+"'"+request.POST['image_url']+"'"+"/>"
post.save()
#return redirect('show_posts')
#return render(request, 'authors/index.html', {'form':form})
if imageForm.is_valid():
image = Image(imageFile=request.FILES['imageFile'])
image.post = post
image.save()
content = post.content
print("image url: %s"%image.imageFile.url)
imgUrl = "https://mighty-cliffs-82717.herokuapp.com/media/" + image.imageFile.url
#this will work for mighty cliffs but not for local testing
#imgUrl = post.source + "media/"+image.imageFile.url
print("imgUrl: %s"%imgUrl)
post.content = content + "<br><img src="+"'"+imgUrl+"'"+"/>"
post.save()
print("post.content: %s"%post.content)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
else:
form = PostForm()
return render(request, 'authors/index.html', {'form':form})
示例14: compile
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def compile(content_path, compile_path, stylesheet, html_template):
(mds, other) = sep_filetype(content_path, ".md")
# Prepare dir structure in compile_path
if os.path.isdir(compile_path):
shutil.move(compile_path, compile_path + ".old")
os.mkdir(compile_path)
new_dirs = [os.path.dirname(path.replace(content_path,
compile_path))
for path in (mds + other)]
for d in new_dirs:
os.makedirs(d, exist_ok=True)
# Copy all non md files
for f in other:
new_path = f.replace(content_path, compile_path)
# Coply file to new path, but don't follow symlinks!
shutil.copy2(f, new_path, follow_symlinks=False)
for f in mds:
with open(f, "r") as md_f:
md = md_f.read()
# Going to use simple str.format to build html to avoid deps with
# templating languages
with open(html_template, 'r') as template_f:
template = template_f.read()
compiled_html = template.format(body=CommonMark.commonmark(md),
stylesheet=stylesheet)
new_path = f.replace(content_path, compile_path)
new_path = os.path.splitext(new_path)[0] + ".html"
with open(new_path, "w") as html_f:
html_f.write(compiled_html)
if os.path.isdir(compile_path + ".old"):
shutil.rmtree(compile_path + ".old")
示例15: markdown
# 需要导入模块: import CommonMark [as 别名]
# 或者: from CommonMark import commonmark [as 别名]
def markdown(src):
return mark_safe(CommonMark.commonmark(force_text(src)))