示例#1
0
文件: filter.py 项目: 4416/hazel-cms
def markdown(text,*args):
    try:
        from lib import markdown2
    except ImportError:
        info("Error in `markdown` filter: The Python markdown2 library isn't installed.")
        return text
    return markdown2.markdown(text,extras=args)
示例#2
0
    def internal_get(self):
        if LLNews.all().count() > 0:
            all_news = LLNews.all().order("-date_created")
            latest_news = all_news.fetch(1)[0]
            latest_news.markdown_html = markdown2.markdown(latest_news.text)

            tri_news = all_news.fetch(3, offset=1)
            for news in tri_news:
                news.markdown_html = markdown2.markdown(news.text)

            news_list = all_news.fetch(5, offset=4)

            values = {"latest": latest_news, "tri_news": tri_news, "news_list": news_list}
            self.render("index", template_values=values)
        else:
            self.render("index")
示例#3
0
  def POST(self): 
      # First, try setting up a dummy SMART client to test the credentials
      # for securty reasons (will raise excepton if the credentails are bad)
      get_smart_client()
  
      # Load the message parameters
      me = SMTP_USER + "@" + SMTP_HOST # we always use the primary SMART Direct address
      you = web.input().recipient_email
      subject = web.input().subject
      message = web.input().message
 
      # Create the body of the message (plain-text and HTML version).
      text = message
      html = markdown(text)
      
      # Generate the PDF attachment content
      pdf_buffer = generate_pdf (html)
      
      # Initialize the attachment and general settings for the mailer
      attachments = [{'file_buffer': generate_pdf(html), 'name': "patient.pdf", 'mime': "application/pdf"}]
      settings = {'host': SMTP_HOST, 'user': SMTP_USER, 'password': SMTP_PASS}
      
      # Send the SMART Direct message
      send_message (me, you, subject, text, html, attachments, settings)
      
      # Clean up the string buffer
      pdf_buffer.close()
      
      # Respond with success message
      return json.dumps({'result': 'ok'})
示例#4
0
    def POST(self):
        # Initialize the SMART client (will raise excepton if the credentails are bad)
        smart_client = get_smart_client()

        # Load the message parameters
        me = SMTP_USER + "@" + SMTP_HOST  # we always use the primary SMART Direct address
        you = web.input().recipient_email
        subject = web.input().subject
        message = web.input().message

        # Create the body of the message (plain-text and HTML version).
        text = message
        html = markdown(text)

        # Generate the PDF attachment content
        pdf_buffer = generate_pdf(html)

        # Initialize the attachment and general settings for the mailer
        attachments = [{"file_buffer": generate_pdf(html), "name": "patient.pdf", "mime": "application/pdf"}]
        settings = {"host": SMTP_HOST, "user": SMTP_USER, "password": SMTP_PASS}

        # Send the SMART Direct message
        send_message(me, you, subject, text, html, attachments, settings)

        # Clean up the string buffer
        pdf_buffer.close()

        # If needed, add the recipient to the app's preferences
        if web.input().recipient_add == "true":
            add_recipient(smart_client, you)

        # Respond with success message
        return json.dumps({"result": "ok"})
示例#5
0
 def markdown(value, video_embed=False):
     # real line breaks
     value = re.sub(r'(\S ?)(\r\n|\r|\n)', r'\1  \n', value)
     # vimeo and youtube embed
     value = re.sub(r'(?:^|\s)http://(?:www\.)?vimeo\.com/(\d+)',
                    r'VIMEO:\1', value)
     value = re.sub(
         r'(?:^|\s)http://www\.youtube\.com/watch\?\S*v=([^&\s]+)\S*',
         r'YOUTUBE:\1', value)
     # automatic hyperlinks
     value = re.sub(r'(^|\s)(http:\/\/\S+)', r'[\2](\2)', value)
     html = markdown2.markdown(value, safe_mode='escape')
     if video_embed:
         html = re.sub(
             r'VIMEO:(\d+)',
             r'<iframe src="http://player.vimeo.com/video/\1" class="video" frameborder="0"></iframe>',
             html)
         html = re.sub(
             r'YOUTUBE:([\w|-]+)',
             r'<iframe src="http://www.youtube.com/embed/\1?hd=1" class="video" frameborder="0"></iframe>',
             html)
     else:
         html = re.sub(
             r'VIMEO:(\d+)',
             r'<a href="http://vimeo.com/\1" data-embed="http://player.vimeo.com/video/\1" class="video">http://vimeo.com/\1</a>',
             html)
         html = re.sub(
             r'YOUTUBE:([\w|-]+)',
             r'<a href="http://www.youtube.com/watch?v=\1" data-embed="http://www.youtube.com/embed/\1?hd=1" class="video">http://www.youtube.com/watch?v=\1</a>',
             html)
     html = html.replace('<a href=', '<a rel="nofollow" href=')
     return html
示例#6
0
	def internal_get(self):
		if LLNews.all().count() > 0:
			all_news = LLNews.all().order('-date_created')
			latest_news = all_news.fetch(1)[0]
			latest_news.markdown_html = markdown2.markdown(latest_news.text)
			
			tri_news = all_news.fetch(3,offset=1)
			for news in tri_news:
				news.markdown_html = markdown2.markdown(news.text)			
			
			news_list = all_news.fetch(5,offset=4)
			
			values = {'latest':latest_news,'tri_news':tri_news,'news_list':news_list}
			self.render('index',template_values=values)
		else:
			self.render('index')
示例#7
0
def make_entry(rec):
    """docstring for make_entry"""
    body = rec.get('body')
    body_html = markdown2.markdown(body)
    rec.update({'body_html': body_html})
    slug = rec.get('slug')
    title = rec.get('title')
    excerpt = rec.get('excerpt')
    markdown = rec.get('markdown') or 'markdown'
    tags = rec.get('tags') or []
    if len(tags) == 0:
        tags = ['general']
    tags = [db.Category(utils.slugify(tag)) for tag in tags if tag]
    
    static = rec.get('static')
    
    if not slug:
        utils.slugify(title)
        
    if not excerpt:
        soup = BeautifulSoup.BeautifulSoup(body_html)
        paras = soup.findAll('p')
        if paras:
            excerpt = paras[0].string
    return Entry(author=users.get_current_user(),
    title=title,
    slug=slug,
    body=body,
    body_html=body_html,
    markdown=markdown,
    excerpt=excerpt,
    tags= tags,
    static=static,
    )
示例#8
0
  def POST(self): 
      # Initialize the SMART client (will raise excepton if the credentails are bad)
      smart_client = get_smart_client()
  
      # Load the message parameters
      me = SMTP_USER + "@" + SMTP_HOST # we always use the primary SMART Direct address
      you = web.input().recipient_email
      subject = web.input().subject
      message = web.input().message
 
      # Create the body of the message (plain-text and HTML version).
      text = message
      html = markdown(text)
      
      # Generate the PDF attachment content
      pdf_buffer = generate_pdf (html)
      
      # Initialize the attachment and general settings for the mailer
      attachments = [{'file_buffer': generate_pdf(html), 'name': "patient.pdf", 'mime': "application/pdf"}]
      settings = {'host': SMTP_HOST, 'user': SMTP_USER, 'password': SMTP_PASS}
      
      # Send the SMART Direct message
      send_message (me, you, subject, text, html, attachments, settings)
      
      # Clean up the string buffer
      pdf_buffer.close()
      
      # If needed, add the recipient to the app's preferences
      if web.input().recipient_add == "true": add_recipient (smart_client, you)
      
      # Respond with success message
      return json.dumps({'result': 'ok'})
示例#9
0
def to_html(body,markdown):
    if markdown == 'markdown':
        body_html = markdown2.markdown(body)
    elif markdown == 'textile':
        body_html = textile.textile(body,)
    else:
        body_html = body
    return body_html
示例#10
0
def to_html(body, markdown):
    if markdown == 'markdown':
        body_html = markdown2.markdown(body)
    elif markdown == 'textile':
        body_html = textile.textile(body, )
    else:
        body_html = body
    return body_html
示例#11
0
def md2_to_html(content):
    ''' convert markdown to html
        using markdown2
    '''
    if content:
        content_html = markdown(content, extras=['code-color'])
        return content_html
    else:
        return 0
示例#12
0
文件: utils.py 项目: zxt/gaeblogz
def md_to_html(text):
    if text:
        html_text = markdown(text, extras=['fenced-code-blocks',
                                           'code_friendly',
                                           'footnotes',
                                           'smarty-pants'])
        return html_text
    else:
        return ""
示例#13
0
	def internal_get(self,slug):
		post = LLNews.all().filter('slug =',slug).get()

		if post is not None:
			markdown_html = markdown2.markdown(post.text)
			values = {'post':post,'from':self.request.path,'markdown_html':markdown_html}
			self.render('view',template_values=values)
		else:
			self.set_flash('No existe esa noticia',flash_type='errorFlash')
			self.redirect('/news/')
示例#14
0
文件: utils.py 项目: zxt/gaeblogz
def md_to_html(text):
    if text:
        html_text = markdown(text,
                             extras=[
                                 'fenced-code-blocks', 'code_friendly',
                                 'footnotes', 'smarty-pants'
                             ])
        return html_text
    else:
        return ""
示例#15
0
	def view_post(self,slug):
		post = LLArticle.all().filter('slug =',slug).get()

		if post is not None:
			markdown_html = markdown2.markdown(post.text,extras={"code-friendly":None,"html-classes":{"pre":"prettyprint"}})
			values = {'post':post,'from':self.request.path,'markdown_html':markdown_html}
			self.render('view_post',template_values=values)
		else:
			self.set_flash('No existe ese post',flash_type='errorFlash')
			self.redirect('/posts/')
示例#16
0
    def internal_get(self, slug):
        post = LLNews.all().filter("slug =", slug).get()

        if post is not None:
            markdown_html = markdown2.markdown(post.text)
            values = {"post": post, "from": self.request.path, "markdown_html": markdown_html}
            self.render("view", template_values=values)
        else:
            self.set_flash("No existe esa noticia", flash_type="errorFlash")
            self.redirect("/news/")
示例#17
0
 def view_posts(self, posts):
     if posts:
         for p in posts:
             p.tdelta = elapsed_human_time(datetime.datetime.now(),
                                           p.birthday)
             p.body = markdown(p.body, output="html5")
                                           
         self.render('view-blog.html', posts=posts)
     else:
         self.redirect('/404', abort=True)        
示例#18
0
def wiki(pagina="home"):
    dados_view['form'] = False
    dados_view['conteudo'] = None
    dados_view['pagina'] = pagina
    pagina = './wiki/%s.md' % pagina

    if (path.exists(pagina)):
        arquivo = open(pagina, 'r')
        dados_view['conteudo'] = markdown(arquivo.read())
        arquivo.close()

    return dados_view
示例#19
0
    def view_post(self, slug):
        post = LLArticle.all().filter("slug =", slug).get()

        if post is not None:
            markdown_html = markdown2.markdown(
                post.text, extras={"code-friendly": None, "html-classes": {"pre": "prettyprint"}}
            )
            values = {"post": post, "from": self.request.path, "markdown_html": markdown_html}
            self.render("view_post", template_values=values)
        else:
            self.set_flash("No existe ese post", flash_type="errorFlash")
            self.redirect("/posts/")
示例#20
0
    def internal_get(self, slug):
        news = LLNews.all().filter("slug =", slug).get()

        if news is not None:
            if news.short_url is None:
                news.short_url = bitly_url("/news/" + slug)
                news.put()
            markdown_html = markdown2.markdown(news.text)
            values = {"news": news, "from": self.request.path, "markdown_html": markdown_html}
            self.render("view", template_values=values)
        else:
            self.set_flash("No existe esa noticia", flash_type="errorFlash")
            self.redirect("/news/")
示例#21
0
	def internal_get(self,slug):
		news = LLNews.all().filter('slug =',slug).get()

		if news is not None:
			if news.short_url is None:
				news.short_url = bitly_url("/news/"+slug)
				news.put()
			markdown_html = markdown2.markdown(news.text)
			values = {'news':news,'from':self.request.path,'markdown_html':markdown_html}
			self.render('view',template_values=values)
		else:
			self.set_flash('No existe esa noticia',flash_type='errorFlash')
			self.redirect('/news/')
示例#22
0
	def internal_get(self):
		offset = 0
		try:
			if(self.request.get('offset') is not None):
				offset=int(self.request.get('offset'))
		except:
			pass
		if LLArticle.all().count() > 0:
			articles = LLArticle.all().order('-date_created').fetch(10,offset)
			for article in articles:
				article.markdown_html = markdown2.markdown(article.text,extras={"code-friendly":None,"html-classes":{"pre":"prettyprint"}})
			values = {'articles':articles,'offset':offset+10,'is_offset':len(articles)>10}
			self.render('index',template_values=values)
		else:
			self.render('index')
示例#23
0
 def internal_get(self):
     offset = 0
     try:
         if self.request.get("offset") is not None:
             offset = int(self.request.get("offset"))
     except:
         pass
     if LLArticle.all().count() > 0:
         articles = LLArticle.all().order("-date_created").fetch(10, offset)
         for article in articles:
             article.markdown_html = markdown2.markdown(
                 article.text, extras={"code-friendly": None, "html-classes": {"pre": "prettyprint"}}
             )
         values = {"articles": articles, "offset": offset + 10, "is_offset": len(articles) > 10}
         self.render("index", template_values=values)
     else:
         self.render("index")
示例#24
0
 def post(self):
     author = users.get_current_user()
     title = escape(self.request.get("title"))
     link = escape(self.request.get("link"))
     description = escape(self.request.get("description"))
     tagsrc = self.request.get("tagsrc")
     srclink = escape(self.request.get("srclink"))
     deschtml = markdown2.markdown(description)
     tags = tagsrc.split(' ')
     
     ws = WebSite(author=author, title=title, link=link,
         description=description, srclink=srclink, is_public=False,
         deschtml=deschtml)
     ws.update_screencap()
     ws.tags_spc = tagsrc
     ws.save()
     self.render('submit_success.html')
	def GetPostContent(self, view, all_lines_in_page, is_markdown):
		post_content = self.CombineContent(self.view, all_lines_in_page)

		# Can be dropped? Should not be required anymore as markdown2 is a submodule.
		# can_markdown = False
		# try: 
		# 	if int(sublime.version()) >= 3000:
		# 		from . import markdown2		
		# 	else:
		# 		import markdown2 # markdown

		# 	can_markdown = True
		# except ImportError:
		# 	can_markdown = False

		# markdown content
		if is_markdown: # and can_markdown:
			post_content = str(markdown2.markdown(post_content,extras=["code-friendly"]))

		return post_content
示例#26
0
    def post(self):
        author = users.get_current_user()
        title = escape(self.request.get("title"))
        link = escape(self.request.get("link"))
        description = escape(self.request.get("description"))
        tagsrc = self.request.get("tagsrc")
        srclink = escape(self.request.get("srclink"))
        deschtml = markdown2.markdown(description)
        tags = tagsrc.split(' ')

        ws = WebSite(author=author,
                     title=title,
                     link=link,
                     description=description,
                     srclink=srclink,
                     is_public=False,
                     deschtml=deschtml)
        ws.update_screencap()
        ws.tags_spc = tagsrc
        ws.save()
        self.render('submit_success.html')
示例#27
0
文件: views.py 项目: csytan/webnodes
 def markdown(value, video_embed=False):
     # real line breaks
     value = re.sub(r'(\S ?)(\r\n|\r|\n)', r'\1  \n', value)
     # vimeo and youtube embed
     value = re.sub(r'(?:^|\s)http://(?:www\.)?vimeo\.com/(\d+)', r'VIMEO:\1', value)
     value = re.sub(r'(?:^|\s)http://www\.youtube\.com/watch\?\S*v=([^&\s]+)\S*', r'YOUTUBE:\1', value)
     # automatic hyperlinks
     value = re.sub(r'(^|\s)(http:\/\/\S+)', r'[\2](\2)', value)
     html = markdown2.markdown(value, safe_mode='escape')
     if video_embed:
         html = re.sub(r'VIMEO:(\d+)', 
             r'<iframe src="http://player.vimeo.com/video/\1" class="video" frameborder="0"></iframe>', html)
         html = re.sub(r'YOUTUBE:([\w|-]+)', 
             r'<iframe src="http://www.youtube.com/embed/\1?hd=1" class="video" frameborder="0"></iframe>', html)
     else:
         html = re.sub(r'VIMEO:(\d+)', 
             r'<a href="http://vimeo.com/\1" data-embed="http://player.vimeo.com/video/\1" class="video">http://vimeo.com/\1</a>', html)
         html = re.sub(r'YOUTUBE:([\w|-]+)', 
             r'<a href="http://www.youtube.com/watch?v=\1" data-embed="http://www.youtube.com/embed/\1?hd=1" class="video">http://www.youtube.com/watch?v=\1</a>', html)
     html = html.replace('<a href=', '<a rel="nofollow" href=')
     return html
示例#28
0
	def __markdown(self):
		self.data = markdown.markdown(self.data, extras=["cuddled-lists","wiki-tables","nofollow"])
示例#29
0
def to_html(body):
    body_html = markdown2.markdown(body)
    return body_html
示例#30
0
def process_blog_posts():
    '''
    Migrates the text files contained in the 'posts' directory to the database.
    These files will have their meta-data removed and their markdown
    interpreted and converted to HTML.

    NOTE: This is only run once -- when the server starts.
    '''

    # Open every blog post
    path = 'posts/'
    for input_file in os.listdir(path):
        if RE_VALID_FILE_EXTENSIONS.search(input_file):

            # Extract date from filename
            try:
                (yy, mm, dd) = input_file.split('-')[:3]
                yy = int('20' + yy) if len(yy) is 2 else int(yy)
                mm = int(mm)
                dd = int(dd)
            except:
                LOGGER.warning('Ignoring file <%s>.  Invalid formatting.' %
                               (input_file, ))
                continue

            # Validate date
            if yy > 2500 or mm > 12 or dd > 31:
                LOGGER.warning('Ignoring file <%s>.  Invalid date range.' %
                               (input_file, ))
                continue

            # Open the file
            file_handle = open(path + input_file, 'r')
            contents = file_handle.read().decode('utf-8')

            # Find the slug
            slug = input_file.split('-', 3)[-1]
            slug = RE_VALID_FILE_EXTENSIONS.sub('', slug)

            # Extract metadata
            meta = {'title': slug, 'author': AUTHOR}
            for tag in METADATA_TAGS:
                re_meta = re.compile(r'''(?:\:%s )(.*?)[\n\r]''' % tag)
                if re_meta.search(contents):
                    meta[tag] = re_meta.findall(contents)[0]
                    contents = re_meta.sub('', contents)

            # Strip the contents of supurfluous whitespace -- now that the
            # metatags have been removed.
            contents = contents.strip()

            # Populate the summary
            # Look for the SUMMARY_DELIM character sequence and use it to
            # form the summary, if it exists.  Otherwise, simply take the first
            # paragraph of the post.
            summary = None
            if re.search(SUMMARY_DELIMITER, contents):  # Use delimiter
                summary = contents.split(SUMMARY_DELIMITER)[0]
                contents = re.sub(SUMMARY_DELIMITER, '', contents)
            else:  # Use first paragraph
                summary = re.split(r'''[\r\n]{2}''', contents)[0]
            html_summary = markdown(summary)

            locator = '/%04d/%02d/%02d/%s' % (
                yy,
                mm,
                dd,
                slug,
            )

            # Enter the file into the database
            html_contents = markdown(contents)
            POSTS[locator] = \
                BlogPost(\
                    date=datetime.date(yy, mm, dd),\
                    meta=meta,\
                    summary=html_summary,\
                    contents=html_contents,\
                    locator=locator\
                    )

            # Remove the file
            file_handle.close()

    KEY_LIST.extend(POSTS.keys())
    KEY_LIST.sort(reverse=True)
示例#31
0
文件: hobo.py 项目: Epictetus/hobo-1
def process_blog_posts():
    '''
    Migrates the text files contained in the 'posts' directory to the database.
    These files will have their meta-data removed and their markdown
    interpreted and converted to HTML.

    NOTE: This is only run once -- when the server starts.
    '''

    global POSTS
    global KEY_LIST

    # Open every blog post
    path = 'posts/'
    for input_file in os.listdir(path):
        if RE_VALID_FILE_EXTENSIONS.search(input_file):

            # Extract date from filename
            try:
                (yy, mm, dd) = input_file.split('-')[:3]
                yy = int('20' + yy) if len(yy) is 2 else int(yy)
                mm = int(mm)
                dd = int(dd)
            except:
                LOGGER.warning('Ignoring file <%s>.  Invalid formatting.' %
                        (input_file,))
                continue

            # Validate date
            if yy > 2500 or mm > 12 or dd > 31:
                LOGGER.warning('Ignoring file <%s>.  Invalid date range.' %
                        (input_file,))
                continue

            # Open the file
            file_handle = open(path + input_file, 'r')
            contents = file_handle.read().decode('utf-8')

            # Extract metadata
            slug = input_file.split('-', 3)[-1]
            slug = RE_VALID_FILE_EXTENSIONS.sub('', slug)
            article_title = slug
            try:
                article_title = RE_ARTICLE_TITLE.findall(contents)[0]
                contents = RE_ARTICLE_TITLE.sub('', contents)
            except:
                LOGGER.warning('Ignoring file <%s>.  Invalid metadata.' %
                        (input_file,))
                continue

            # Strip the contents of supurfluous whitespace -- now that the
            # metatags have been removed.
            contents = contents.strip()

            # Populate the summary
            # Look for the SUMMARY_DELIM character sequence and use it to
            # form the summary, if it exists.  Otherwise, simply take the first
            # paragraph of the post.
            summary = None
            if re.search(SUMMARY_DELIM, contents):  # Use delimiter
                summary = contents.split(SUMMARY_DELIM)[0]
                contents = re.sub(SUMMARY_DELIM, '', contents)
            else:                                   # Use first paragraph
                summary = re.split(r'''[\r\n]{2}''', contents)[0]
            html_summary = markdown(summary)

            locator = '/%04d/%02d/%02d/%s' % (yy, mm, dd, slug, )

            # Enter the file into the database
            html_contents = markdown(contents)
            POSTS[locator] = \
                BlogPost(\
                    date=datetime.date(yy, mm, dd),\
                    title=article_title,\
                    author=AUTHOR,\
                    summary=html_summary,\
                    contents=html_contents,\
                    locator=locator\
                    )

            # Remove the file
            file_handle.close()

    KEY_LIST = POSTS.keys()
    KEY_LIST.sort(reverse=True)