Python markdown 模块,markdown() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用markdown.markdown()。
def edit_message(id):
"""
Modify an existing message.
This endpoint is requires a valid user token.
Note: users are only allowed to modify their own messages.
"""
msg = Message.query.get_or_404(id)
if msg.user_id != g.jwt_claims.get('user_id'):
abort(403)
msg.from_dict(request.get_json() or {})
db.session.add(msg)
db.session.commit()
# render the markdown and expand the links in a background task
if app.config['TESTING']:
# for unit tests,render synchronously
render_message(msg.id)
else:
# asynchronous rendering
render_thread = threading.Thread(target=render_message,
args=(msg.id,))
render_thread.start()
return '', 204
def lookup_course_review(db, review_id):
# perform sql query
cur = db.cursor()
qry = 'SELECT * FROM CourseReview WHERE Id = %s'
cur.execute(qry, [review_id])
# process results
row = cur.fetchone()
if row is None:
log('W', 'record', 'CourseReview %d not found. Skipping.' % review_id)
return None
res = {}
for idx, elem in enumerate(row):
# encode strings (unicode strings due to utf-8)
# if type(elem) == type(u''):
# elem = elem.replace('"','\\"').replace('\n','\\n')
# elem = elem.encode(encoding='utf-8')
if TABLE_STRUCT['CourseReview'][idx] in MARKDOWN_FIELDS:
elem = markdown(elem)
res[TABLE_STRUCT['CourseReview'][idx]] = elem
return res
def lookup_prof_review(db, review_id):
# perform sql query
cur = db.cursor()
qry = 'SELECT * FROM ProfReview WHERE Id = %s'
cur.execute(qry, 'ProfReview %d not found. Skipping' % review_id)
return None
res = {}
for idx, elem in enumerate(row):
# encode unicode strings
# if type(elem) == type(u''):
# elem = elem.encode(encoding='utf-8')
# elem = elem.replace('"','<br>')
if TABLE_STRUCT['ProfReview'][idx] in MARKDOWN_FIELDS:
elem = markdown(elem)
res[TABLE_STRUCT['ProfReview'][idx]] = elem
return res
def lookup_course_review(db,'\\n')
# elem = elem.encode(encoding='utf-8')
if TABLE_STRUCT['CourseReview'][idx] in MARKDOWN_FIELDS:
elem = markdown(elem)
res[TABLE_STRUCT['CourseReview'][idx]] = elem
return res
def lookup_prof_review(db,'<br>')
if TABLE_STRUCT['ProfReview'][idx] in MARKDOWN_FIELDS:
elem = markdown(elem)
res[TABLE_STRUCT['ProfReview'][idx]] = elem
return res
def generate_doc(config):
docdir = os.path.join(cwd,'documentation')
if not os.path.exists(docdir):
docdir = os.path.join(cwd,'..','documentation')
if not os.path.exists(docdir):
print "Couldn't find documentation file at: %s" % docdir
return None
try:
import markdown2 as markdown
except ImportError:
import markdown
documentation = []
for file in os.listdir(docdir):
if file in ignoreFiles or os.path.isdir(os.path.join(docdir, file)):
continue
md = open(os.path.join(docdir,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def get(self, topic_id):
'''
?????
'''
topic = dict()
tid = ObjectId(topic_id)
topic = yield self.db.topic.find_one({
'_id': tid
})
if topic is None:
self.custom_error()
isfavorite = False
current_user = self.current_user
topic['content'] = markdown.markdown(topic['content'])
isfavorite = False
if current_user:
user = yield self.db.user.find_one({
'_id': ObjectId(current_user['_id'])
})
if topic['_id'] in user['favorite']:
isfavorite = True
self.render('topic/template/topic-detail.html',
topic=topic, isfavorite=isfavorite)
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def markdown(text, *args, **kwargs):
"""Convert a Markdown string to HTML and return HTML as a Unicode string.
This is a shortcut function for `Markdown` class to cover the most
basic use case. It initializes an instance of Markdown,loads the
necessary extensions and runs the parser on the given text.
Keyword arguments:
* text: Markdown formatted text as Unicode or ASCII string.
* Any arguments accepted by the Markdown class.
Returns: An HTML document as a string.
"""
md = Markdown(*args, **kwargs)
return md.convert(text)
def blog_search(request,):
search_for = request.GET['search_for']
if search_for:
results = []
article_list = get_list_or_404(Article)
category_list = get_list_or_404(Category)
for article in article_list:
if re.findall(search_for, article.title):
results.append(article)
for article in results:
article.body = markdown.markdown(article.body, )
tag_list = Tag.objects.all().order_by('name')
return render(request, 'blog/search.html', {'article_list': results,
'category_list': category_list,
'tag_list': tag_list})
else:
return redirect('app:index')
def new_message():
"""
Post a new message.
This endpoint is requires a valid user token.
"""
msg = Message(user_id=g.jwt_claims['user_id'])
msg.from_dict(request.get_json(), partial_update=False)
msg.html = '...'
db.session.add(msg)
db.session.commit()
r = jsonify(msg.to_dict())
r.status_code = 201
r.headers['Location'] = url_for('get_message', id=msg.id)
# render the markdown and expand the links in a background task
if app.config['TESTING']:
# for unit tests,))
render_thread.start()
return r
def post_comment(request,post_pk):
post=get_object_or_404(Post,pk=post_pk)
post.body=markdown.markdown(post.body,extensions=[ 'markdown.extensions.extra',
'markdown.extensions.codehilite',
'markdown.extensions.toc',])
if request.method=="POST":
form = CommentsForm(request.POST)
if form.is_valid():
comment=form.save(commit=False)
comment.post=post
comment.save()
return redirect(post)
else:
comment_list = post.comment_set.all()
context={
'post':post,
'form':form,
'comment_list':comment_list,
}
return render(request,'blog/detail.html',context=context)
return redirect(post)
def get_context_data(self, **kwargs):
context = super(LinkDetail, self).get_context_data(**kwargs)
if self.request.user.is_authenticated():
is_fav = self.request.user.favourites.filter(
id=self.object.id
).exists()
context['favourite'] = is_fav
context['not_lighthouse_link'] = self.object.id not in [1, 2]
if self.object.description is not None:
html = markdown.markdown(self.object.description)
context['html_description'] = html
else:
context['html_description'] = ''
return context
def get_context_data(self, **kwargs):
context = super(StaticPageViewBase, self).get_context_data(**kwargs)
if not self.slug:
self.slug = kwargs['slug']
filename = self.get_markdown_filename()
try:
input_file = codecs.open(
filename,
mode="r",
encoding="utf-8"
)
except FileNotFoundError:
raise Http404
text = input_file.read()
html = markdown.markdown(text)
context['html_content'] = html
return context
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def registerExtensions(self, extensions, configs):
"""
Register extensions with this instance of Markdown.
Keyword arguments:
* extensions: A list of extensions,which can either
be strings or objects. See the docstring on Markdown.
* configs: A dictionary mapping module names to config options.
"""
for ext in extensions:
if isinstance(ext, util.string_type):
ext = self.build_extension(ext, configs.get(ext, []))
if isinstance(ext, Extension):
ext.extendMarkdown(self, globals())
elif ext is not None:
raise TypeError(
'Extension "%s.%s" must be of type: "markdown.Extension"'
% (ext.__class__.__module__, ext.__class__.__name__))
return self
def convert_markdown_file(input_file):
# input_file = 'README.md'
output_file = input_file.split('.')[0]
with open(input_file, 'r') as rhandler:
# markdown
mdcontent = rhandler.read()
marked_content, quotes = fix_quotes(mdcontent)
# HTML
html = markdown(marked_content)
# text
marked_text = html2text.html2text(html)
text = fix_text(marked_text, quotes)
with open(output_file, 'w') as whandler:
whandler.write(text)
def tutorials():
"""
Route: /tutorials
This route will render the tutorials page. Note that the markdown tutorial
files are read when the application starts-up.
"""
global TUTORIALS
if flask.request.method != "GET":
return flask.abort(400)
if len(TUTORIALS) == 0:
return flask.render_template("tutorials.html",
show_logout_button=l.is_logged_in(),
error="No tutorials to show")
if DEBUG:
TUTORIALS = []
populate_tutorials()
return flask.render_template("tutorials.html",
show_logout_button=l.is_logged_in(),
tutorials=TUTORIALS)
def markdown_extract(text, extract_length=190):
''' return the plain text representation of markdown encoded text. That
is the texted without any html tags. If extract_length is 0 then it
will not be truncated.'''
if not text:
return ''
plain = RE_MD_HTML_TAGS.sub('', markdown(text))
if not extract_length or len(plain) < extract_length:
return literal(plain)
return literal(
unicode(
whtext.truncate(
plain,
length=extract_length,
indicator='...',
whole_word=True
)
)
)
def render_markdown(data, auto_link=True, allow_html=False):
''' Returns the data as rendered markdown
:param auto_link: Should ckan specific links be created e.g. `group:xxx`
:type auto_link: bool
:param allow_html: If True then html entities in the markdown data.
This is dangerous if users have added malicIoUs content.
If False all html tags are removed.
:type allow_html: bool
'''
if not data:
return ''
if allow_html:
data = markdown(data.strip())
else:
data = RE_MD_HTML_TAGS.sub('', data.strip())
data = clean_html(
markdown(data), strip=True,
tags=MARKDOWN_TAGS, attributes=MARKDOWN_ATTRIBUTES)
# tags can be added by tag:... or tag:"...." and a link will be made
# from it
if auto_link:
data = html_auto_link(data)
return literal(data)
def registerExtensions(self, {}))
if isinstance(ext, globals())
logger.info('Successfully loaded extension "%s.%s".'
% (ext.__class__.__module__, ext.__class__.__name__))
elif ext is not None:
raise TypeError(
'Extension "%s.%s" must be of type: "markdown.Extension"'
% (ext.__class__.__module__, ext.__class__.__name__))
return self
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
body = form.cleaned_data['body']
body_html = markdown.markdown(body)
body_html = bleach.clean(body_html, tags=settings.ARTICLE_TAGS, strip=True)
article = Post(title=title, body=body, user=request.user, body_html=body_html)
article.save()
Vote_obj = VotePost(user=request.user,
post=article,
value=1)
Vote_obj.save()
article.upVotes += 1
article.net_Votes += 1
article.save()
messages.success(request, 'Article has been submitted.')
return redirect(reverse('ploghubapp:home_page') + '?sort_by=new')
else:
return render(request, self.template_name, {'form' : form})
def parse_post(post, external_links=False, create_html=True):
with open(os.path.join(BLOG_CONTENT_DIR, post)) as handle:
raw = handle.read()
frontmatter, content = REGEX_SPLIT_FRONTMATTER.split(raw, 2)
data = yaml.load(frontmatter)
y, m, d, slug = post[:-3].split('-', maxsplit=3)
if create_html:
data['html'] = markdown.markdown(content, extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',
'markdown.extensions.toc'
])
data['url'] = url_for('blog_post', y=y, m=m, d=d, slug=slug,
_external=external_links)
data['reading_time'] = reading_time(content)
return data
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def _get(version=None, path=RELEASE_NOTES_FILE, html='n', display='n'):
'''Return only the release notes for the specified version'''
version = version or get_version()
text = open(path).read()
match = re.search('^(?P<notes># v?{0}.*?)^\*+$\n^$'.format(version), text, re.MULTILINE | re.DOTALL)
if match:
notes = match.group('notes').strip()
if true(html):
notes = markdown(notes, extensions=['markdown.extensions.fenced_code'])
if true(display):
print(notes)
return notes
print("WARNING: No release notes found for [%s]" % version)
def safe_markdown(comment, extensions=[]):
html = markdown.markdown(comment, extensions=extensions)
return bleach.clean(
text=html,
tags=[
'a', 'abbr', 'acronym', 'b', 'blockqote', 'code', 'em', 'i', 'li',
'ol', 'strong', 'ul', 'p', 'span', 'h1', 'h2', 'h3', 'pre',
'blockquote', 'table', 'thead', 'tr', 'th', 'td', 'tbody', 'dl',
'dt', 'sup', 'div', 'hr',
],
attributes={
'*': ['class'],
'a': ['href', 'title', 'class', 'id'],
'acronym': ['title'],
'abbr': ['title'],
'sup': ['id'],
'li': ['id']
},
)
def html_doc(self):
"""Methods docstring,as HTML"""
if not self.raw_docstring:
result = ''
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'):
from docutils.core import publish_parts
result = publish_parts(self.raw_docstring, writer_name='html')['body']
elif settings.MODERNRPC_DOC_FORMAT.lower() in ('md', 'markdown'):
import markdown
result = markdown.markdown(self.raw_docstring)
else:
result = "<p>{}</p>".format(self.raw_docstring.replace('\n\n', '</p><p>').replace('\n', ' '))
return mark_safe(urlize(result))
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def comment(request, key=''):
t = Ticket.objects.\
filter(key=key).\
prefetch_related('watchers').\
prefetch_related('comments').\
all()
if len(t) == 0:
raise Http404('No ticket with that key found.')
if not request.user.has_perm('projects.add_comments', t[0].project):
raise PermissionDenied
c = Comment(body=request.POST['body'], author=request.user, ticket=t[0])
c.save()
notify.send(
request.user,
recipient=t[0].watching(),
verb='commented on',
action_object=t[0],
target=t[0].project,
description=markdown.markdown(c.body, safe_mode='escape'))
return redirect('/tickets/' + t[0].key)
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def on_menuitem_export_pdf_activate(self, widget):
self.window.set_sensitive(False)
start, end = self.text_buffer.get_bounds()
text = self.text_buffer.get_text(start, end, False)
text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False)
dirname = os.path.dirname(self.name)
text = re.sub(r'(\!\[.*?\]\()([^/][^:]*?\))', lambda m, dirname=dirname: m.group(1) + os.path.join(dirname, m.group(2)), text)
try:
html_middle = markdown.markdown(text, self.default_extensions)
except:
try:
html_middle = markdown.markdown(text, self.safe_extensions)
except:
html_middle = markdown.markdown(text)
html = self.default_html_start + html_middle + self.default_html_end
self.save_pdf(html)
def on_menuitem_preview_browser_activate(self, widget):
# Create a temporary HTML file
tf = tempfile.NamedTemporaryFile(delete = False)
self.temp_file_list.append(tf)
tf_name = tf.name
text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), extensions =self.safe_extensions)
except:
html_middle = markdown.markdown(text)
html = self.default_html_start + html_middle + self.default_html_end
tf.write(html.encode())
tf.flush()
# Load the temporary HTML file in the user's default browser
webbrowser.open_new_tab(tf_name)
def check_for_updates(self, show = False):
try:
update_check = urlopen("http://remarkableapp.github.io/latest")
latest_version = float(update_check.readline())
if app_version < latest_version:
print("There is a new version avaiable")
subprocess.Popen(['notify-send', "Remarkable: A new version of this app is avaiable"])
update_check = urlopen("http://remarkableapp.github.io/change_log")
md = update_check.read()
html = markdown.markdown(md)
if show:
webbrowser.open_new_tab("http://remarkableapp.github.io")
else:
if show:
subprocess.Popen(['notify-send', "Remarkable: You already have the latest version of this app available"])
print("You have the latest version of this app available")
except:
print("Warning: Remarkable Could not connect to the internet to check for updates")
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def load_posts(directory, mode="post"):
for filename in os.listdir(directory):
post_filename = os.path.join(directory, filename)
with open(post_filename) as post_file:
split_filename = os.path.splitext(filename)
if len(split_filename) == 2 and split_filename[1] == ".md":
if split_filename[1].endswith("_draft"):
cnsl.warn("Skipping draft file {}".format(filename))
continue
cnsl.ok("Compiling {} {}".format(mode, filename))
post_slug = split_filename[0].lower().replace(" ", "-")
new_filename = os.path.join(post_slug, "index.html")
url = "/" + \
os.path.join(
"posts", post_slug) if mode == "post" else "/" + post_slug
content = markdown(post_file.read())
yield {
'filename': new_filename,
'url': url,
'post-title': split_filename[0],
'content': content,
'date': time.ctime(os.path.getctime(post_filename))
}
else:
cnsl.warn("Ignoring file " + filename)
def share(id):
note = Note.query.get_or_404(id)
if current_user != note.author:
abort(403)
form = ShareForm()
if form.validate_on_submit():
send_email(
form.recipient_email.data,
'{0} has shared a braindump with you!'
.format(current_user.email),
'app_email/share_note',
user=current_user, note=note, html=markdown(note.body))
shared = Sharednote(
author_id=current_user.id,
note_id=note.id,
recipient_email=form.recipient_email.data)
db.session.add(shared)
db.session.commit()
flash('The note has been shared!')
return redirect(url_for('.index'))
return render_template('app/share_note.html', form=form, notes=[note])
def registerExtensions(self, ext.__class__.__name__))
return self
def generate_doc(config):
docdir = os.path.join(cwd,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def get(self, name):
self.finish_preload()
contents = StaticContent.query(StaticContent.name == name).fetch(100)
if not contents:
self.response.status = 404
return
if len(contents) > 1:
self.response.status = 500
logging.error('Found too many StaticContentPages: %s', contents)
return
content = contents[0]
rendered_content = markdown.markdown(content.markdown)
self.display['title'] = content.title
self.display['content'] = rendered_content
self.render_template('static_wrapper')
def _repr_html_(self):
return markdown.markdown(self)
def generate_markdown(self):
"""
??markdown
:return:
:rtype:
"""
doc_lines = [u"API Document", u"----------------", u" "]
doc_lines.append(u"<center>")
doc_lines.append(u"### TOC Index")
doc_lines.append(u"</center>")
doc_lines.append(u" ")
doc_lines.append(u"| id | title |")
doc_lines.append(u"|:----- |:--------- |")
for doc_idx, doc in enumerate(self.functions):
doc_lines.append(u"|%s|" % u"|".join([str(doc_idx), doc.link()]))
doc_lines.append(u" ")
doc_lines.append(u"---")
doc_lines.append(u" ")
doc_lines.append(u" ")
for bp in self.blueprint_ins:
doc_lines.append(u"#### %s" % bp.name)
for doc_idx, doc in enumerate(bp.funcs):
doc_lines.append(doc.anchor())
doc_lines.append(doc.gen_markdown())
doc_lines.append(u" ")
doc_lines.append(u"---")
markdown = "\n".join([line.encode('utf8') for line in doc_lines])
return markdown
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。