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
python类markdown()的实例源码
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, [review_id])
# process results
row = cur.fetchone()
if row is None:
log('W', 'record', '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('"', '\\"').replace('\n', '<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, 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, [review_id])
# process results
row = cur.fetchone()
if row is None:
log('W', 'record', '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('"', '\\"').replace('\n', '<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,'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 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 synchronously
render_message(msg.id)
else:
# asynchronous rendering
render_thread = threading.Thread(target=render_message,
args=(msg.id,))
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,'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 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 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 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 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 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 __init__(self, initial=''):
"""Create a Markdown widget.
Parameters
----------
initial : str, optional
Default markdown for the widget.
"""
super(Markdown, self).__init__()
self._comp = self._tag.format(
initial=Markup(markdown(initial).replace('\n', '\\n'))
)
# pylint: disable=no-self-use
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, 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())
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 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 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,'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 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)