本文整理汇总了Python中CommonMark类的典型用法代码示例。如果您正苦于以下问题:Python CommonMark类的具体用法?Python CommonMark怎么用?Python CommonMark使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CommonMark类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: toHTML
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)
示例2: generate_email
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: markdown
def markdown(md, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
html = CommonMark.commonmark(esc(md))
return mark_safe(html)
示例4: test_unicode
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```')
示例5: create_post
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'))
示例6: render
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
示例7: main
def main():
parser = argparse.ArgumentParser(
description="Process Markdown according to "
"the CommonMark specification.")
if sys.version_info < (3, 0):
reload(sys) # noqa
sys.setdefaultencoding('utf-8')
parser.add_argument(
'infile',
nargs="?",
type=argparse.FileType('r'),
default=sys.stdin,
help="Input Markdown file to parse, defaults to STDIN")
parser.add_argument(
'-o',
nargs="?",
type=argparse.FileType('w'),
default=sys.stdout,
help="Output HTML/JSON file, defaults to STDOUT")
parser.add_argument('-a', action="store_true", help="Print formatted AST")
parser.add_argument('-aj', action="store_true", help="Output JSON AST")
args = parser.parse_args()
parser = CommonMark.Parser()
f = args.infile
o = args.o
lines = []
for line in f:
lines.append(line)
data = "".join(lines)
ast = parser.parse(data)
if not args.a and not args.aj:
renderer = CommonMark.HtmlRenderer()
o.write(renderer.render(ast))
exit()
if args.a:
# print ast
CommonMark.dumpAST(ast)
exit()
# o.write(ast.to_JSON())
o.write(CommonMark.dumpJSON(ast))
exit()
示例8: render_markdown
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)
示例9: get_thumbnail_url
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
示例10: report
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)
示例11: post_new
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})
示例12: compile
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")
示例13: test_null_string_bug
def test_null_string_bug(self):
s = CommonMark.commonmark('> sometext\n>\n\n')
self.assertEqual(
s,
'<blockquote>\n<pre><code>sometext\n</code></pre>'
'\n</blockquote>\n')
示例14: test_output
def test_output(self):
s = CommonMark.commonmark('*hello!*')
self.assertEqual(s, '<p><em>hello!</em></p>\n')
示例15: markdown
def markdown(src):
return mark_safe(CommonMark.commonmark(force_text(src)))