示例#1
0
def show_post(id=None):
    if id:
        db = get_db()
        cur = db.execute('select id, title, content from blog where id = ?', [id])
        row = cur.fetchone()
        if row:
            result = []
            content = markdown2.markdown(row["content"], extras=["code-friendly","code-color", "cuddled-lists","tables","footnotes","pyshell","toc"])
            #content = Markup(markdown.markdown(row["content"]))
            result.append((row["id"], row["title"],content))
            return render_template('blog.html', result=result)
            #return render_template('show_blog.html', **locals())
        else:
            abort(404)
    else:
        db = get_db()
        cur = db.execute('select id, title, content from blog where navigation=0 order by id desc')
        rows = cur.fetchall()
        #content = Markup(markdown.markdown(entries))
        #print entries
        result = []
        for row in rows:
            content = markdown2.markdown(row["content"], extras=["code-friendly","code-color", "cuddled-lists","tables","footnotes","pyshell","toc"])

            result.append((row["id"], row["title"], content))
        
        return render_template('blog.html', result=result)
示例#2
0
    def post(self):
        if not self.get_user['admin']:
            self.render('status.html', message=u'对不起你没有权限!')
            return

        title = self.get_argument('title')
        content = self.get_argument('content')
        new_content = []

        # markdown转成html并转义
        title = unicode(markdown2.markdown(escape.html_escape(title)))
        content = unicode(markdown2.markdown(escape.html_escape(content),
                                             extras=['fenced-code-blocks']))

        # 反转义代码块中的"&"
        m = re.compile('\<pre\>[\s\S]*\<\/pre\>')
        content = m.sub(escape.code_unescape, content)

        for span_content in content.split(' '):
            new_content.append(tool.insert_span(span_content))

        content = ' '.join(new_content)

        create_time = datetime.datetime.now()

        news = models.News(title=title, content=content, create_time=create_time)
        news.insert()
        self.render('status.html', message=u'发布新闻成功!')
示例#3
0
 def _create_html_content_from(self, story):
     """Return an html representation of this story."""
     html = StringIO.StringIO()    
     html.write('<html><body>')
     html.write('<a href="' + self.link + '">Story details</a><br />')
     html.write('<b>' + markdown(story['text']) + '</b>')
     if story['details']:
         html.write(markdown(story['details']))
     html.write('<hr />')
     if not story['color'] == 'grey':
         html.write('Color: <span style="color:' + story['color'] + '">'
             + story['color'] + '</span><br />')
     html.write('Phase: ' + story['phase']['name'] + '<br />')
     html.write('Status: ' + story['status'] + '<br />')
     if 'blockedReason' in story.keys():
         html.write('<span style="color:red">Block reason: '
             + story['blockedReason'] + '</span><br />')
     html.write('Creator: ' + story['creator']['name'] + '<br />')
     if 'owner' in story.keys():
         html.write('Owner: ' + story['owner']['name'] + '<br />')
     if 'deadline' in story.keys():
         html.write('Deadline: '
             + re.sub('T00:00:00', '', story['deadline']) + '<br />')
     if story['comments']:
         html.write('<hr /><br />')
     for comment in story['comments']:
         html.write(' <i>' + comment['author']['name'] + '</i> said (')
         html.write(_convert_gmt(comment['createTime']) + '):')
         comment = re.sub('(\n)', '<br />', comment['text'])
         html.write('<p>' + markdown(comment) + '</p>')
         html.write("<br />")        
     html.write('</body></html>')
     content = html.getvalue()
     html.close()
     return content
示例#4
0
def convert():
	markdownInput = open(args.markdown).read() # Read markdown file into markdownInput

	title = markdownInput.split('\n')[:2] # Take the first line and make it the <title>
	block = markdownInput.split('\n')[2:] # Strip the title out of the entry
	block = '\n'.join(block)

	markdownHTML = markdown2.markdown(block) # Convert markdown to HTML

	if args.template:
		title = str(title[0]) 
		template = open('templates/' + args.template).read() # Load template specified by -t flag
	else:
		title = str(title[0]) + '\n' + str(title[1])
		title = markdown2.markdown(title)
		template = "{{title}}\n{{block}}"

	htmlOutput = ''
	for line in template:
		htmlOutput += line # Turns converted read template html to a multi line string, helps for regex subs

	htmlOutput = re.sub("{{title}}", title, htmlOutput) # Sets <title> if not index
	htmlOutput = re.sub("{{datetime}}", datetime.datetime.now().ctime(), htmlOutput) # Insert date and time i.e., Wed Apr 16 17:18:56 2014	
	htmlOutput = re.sub("{{block}}", markdownHTML, htmlOutput) # Insert converted markdown to location of {{block}} in template

	try:
		open('webserver/' + args.markdown.strip(".md") + ".html", "w").write(htmlOutput) # Create html and write it
		print "Generated %s" % (args.markdown.strip('.md') + '.html')
	except IOError:
		print """Path could not be found.  Please make sure the folder hierarchy matches in 
示例#5
0
    def save(self, **kwargs):
        new_revision = not self.id
        silent_update =  kwargs.has_key('silent_update')
        if silent_update:
            kwargs.pop('silent_update')
        if new_revision and self.pub_date is None:
            self.pub_date = datetime.datetime.now()
        if not silent_update:
            self.updated_date = datetime.datetime.now()

        # Use safe_mode in Markdown to prevent arbitrary input
        # and strip all html tags from CharFields
        self.version = strip_tags(self.version)
        self.authors = strip_tags(self.authors)
        self.changes_html = markdown(self.changes, safe_mode=True)
        self.description_html = markdown(self.description, safe_mode=True)
        self.tags = strip_tags(self.tags)
        self.language = strip_tags(self.language)
        self.os_license = strip_tags(self.os_license)
        self.paper_bib = strip_tags(self.paper_bib)
        self.operating_systems = strip_tags(self.operating_systems)
        self.dataformats = strip_tags(self.dataformats)
        super(Revision, self).save(kwargs)

        # Update authorlist, taglist, licenselist, langaugelist, opsyslist
        self.update_list('authorlist','Author','authors')
        self.update_list('taglist','Tag','tags')
        self.update_list('licenselist','License','os_license')
        self.update_list('languagelist','Language','language')
        self.update_list('opsyslist','OpSys','operating_systems')
        self.update_list('dataformatlist','DataFormat','dataformats')

        # send out notifications on updates
        if not silent_update:
            self.software.notify_update()
示例#6
0
def rebuild_cache(f):

    #Grab data from the spreadsheet in one request
    #Comes back as a list of lists
    gdocAsLists = open_spreadsheet()

    #Parse this data into layerName: {'metadata info': 'value'} format
    md = gdoc_lists_to_layer_dict(gdocAsLists)

    with io.open(f, 'w', encoding='utf8') as cache:
        cache.write(u'{')
        i = 0
        for layer in md.keys():
            if i > 0:
                cache.write(u', ')
            cache.write(u'"{0!s}": {{'.format(layer))
            j = 0
            for field in md[layer].keys():
                if j > 0:
                    cache.write(u', ')

                if field in ['title', 'translated_title', 'subtitle', 'tags', 'learn_more', 'download_data', 'agol_id', 'map_service', 'amazon_link']:
                    cache.write(u'"{0!s}": "{1!s}"'.format(field, markdown2.markdown(md[layer][field], extras=["code-friendly"]).strip().replace('{', '\\{').replace('}', '\\}').replace('"', '\\"').replace(u'\n', u'<br>').replace(u'</p><br>', u'</p>').replace(u'<br><p>', u'<p>').replace(u'<p>', u'').replace(u'</p>', u'')))
                else:
                    cache.write(u'"{0!s}": "{1!s}"'.format(field, markdown2.markdown(md[layer][field], extras=["code-friendly"]).strip().replace('{', '\\{').replace('}', '\\}').replace('"', '\\"').replace(u'\n', u'<br>').replace(u'</p><br>', u'</p>').replace(u'<br><p>', u'<p>').replace(u'<p></p>', u'')))

                j += 1
            cache.write(u'}')

            i += 1
        cache.write(u'}')

    print 'done rebuild'
 def render(
     self,
     jobtype="",
     location="",
     title="",
     description="",
     skills="",
     about="",
     company="",
     image="",
     template="job_post.html",
     job_id=1,
 ):
     template_values = {
         "jobtype": jobtype,
         "location": location,
         "title": title,
         "description": markdown2.markdown(description),
         "skills": markdown2.markdown(skills),
         "about": markdown2.markdown(about),
         "company": company,
         "image": image,
         "job_id": job_id,
     }
     template = jinja_environment.get_template(template)
     self.response.out.write(template.render(template_values))
示例#8
0
文件: app.py 项目: evz/tacofancy-api
def preheat():
    index = requests.get('%s/INDEX.md' % base_url)
    soup = BeautifulSoup(md.markdown(index.content))
    links = [a for a in soup.find_all('a') if a.get('href').endswith('.md')]
    full_tacos = [f.get('href') for f in links if 'full_tacos/' in f.get('href')]
    base_layers = [b.get('href') for b in links if 'base_layers/' in b.get('href')]
    mixins = [m.get('href') for m in links if 'mixins/' in m.get('href')]
    condiments = [c.get('href') for c in links if 'condiments/' in c.get('href')]
    seasonings = [s.get('href') for s in links if 'seasonings/' in s.get('href')]
    shells = [s.get('href') for s in links if 'shells/' in s.get('href')]
    bases = get_cookin(BaseLayer, base_layers)
    conds = get_cookin(Condiment, condiments)
    seas = get_cookin(Seasoning, seasonings)
    mix = get_cookin(Mixin, mixins)
    shell = get_cookin(Shell, shells)
    for full_taco in get_cookin(FullTaco, full_tacos):
        soup = BeautifulSoup(md.markdown(full_taco.recipe))
        ingredient_links = [l.get('href') for l in soup.find_all('a') if l.get('href').endswith('.md')]
        for link in ingredient_links:
            parts = urlparse(link).path.split('/')[-2:]
            kind = MAPPER[parts[0]]
            scrubbed_link = '/'.join(parts)
            full_link = '%s/%s' % (base_url, scrubbed_link)
            ingredient = db.session.query(kind).get(full_link)
            if ingredient:
                setattr(full_taco, ingredient.__tablename__, ingredient)
                db.session.add(full_taco)
                db.session.commit()
    return None
示例#9
0
文件: views.py 项目: jimforit/JimBlog
def article_publish(request):
	if request.method == "POST":
		user_name = request.session['username']
		user = User.objects.get(name=user_name)
		article_title = request.POST.get("title")
		abstract = request.POST.get("abstract")
		article_body = request.POST.get("content")
		catogory_name = request.POST.get("category")
		category = Category.objects.get(name=catogory_name)
		article_status = request.POST.get("status")
		article_body = markdown2.markdown(article_body)
		Article.objects.create(title=article_title,body=article_body,status=article_status,abstract=abstract,auther=user,category=category)
	
	article_list = Article.objects.filter(status = 'p')
	for articles in article_list:
			articles.body = markdown2.markdown(articles.body,)
	user_count = User.objects.all().count()
	article_count = Article.objects.all().count()
	latest_login_user = User.objects.all().order_by('-last_login_time')[:5]
	category_list = Category.objects.all().order_by('name')
	popular_article = Article.objects.all().order_by('-likes')[:5]
	views_article = Article.objects.all().order_by('views')[:5]
	new_comment_list = []
	new_comment_list = Comment.objects.filter(comment_reminder=user,comment_status="N")
	comment_count_user = len(new_comment_list)
	return render(request,"index.html",{"comment_list_user":new_comment_list,"comment_count_user":comment_count_user,"latest_login_user":latest_login_user,"user_count":user_count,"article_count":article_count,"article_list":article_list,"category_list":category_list,"popular_article":popular_article,"views_article":views_article})
示例#10
0
文件: views.py 项目: jimforit/JimBlog
def comment_commit(request,article_id):
	article = Article.objects.get(id=article_id)
	article_url = article.get_absolute_url()
	comment_error = ""
	
	if request.method == "POST":
		user_name = request.session["username"]
		user = User.objects.get(name=user_name)
		comment_content = request.POST.get("comment")
		
		if comment_content != "":
			subject = '您有一条来自JimBlog的评论'
			text_content = '#Comment:'+article.title+'\n\n'+user.name+":"+'\n'+comment_content+'\n'+\
			'---------------------------------------------------------------------------'+'\n'+\
			'URL:'+'http://127.0.0.0.1:8000'+article_url
			comment_content = markdown2.markdown(comment_content)
			comment_reminder = User.objects.get(name=article.auther.name)
			from_email = settings.DEFAULT_FROM_EMAIL
			msg = EmailMultiAlternatives(subject, text_content, from_email, [comment_reminder.email])
			msg.send()
			comment_obj = Comment.objects.create(comment_user = user,comment_content = comment_content,article=article,comment_status='N',comment_reminder=comment_reminder)
			
	comment_count = Comment.objects.all().count()
	article.body = markdown2.markdown(article.body)
	category_list = Category.objects.all().order_by('name')
	popular_article = Article.objects.all().order_by('-likes')[:5]
	views_article = Article.objects.all().order_by('views')[:5]
	
	return  HttpResponseRedirect(article_url)
示例#11
0
 def get_object(self, queryset=None):
     obj = super(ATDDDetailView, self).get_object()
     obj.suitename = markdown2.markdown(self.convert_markdown_split_line(obj.suitename), extras=['fenced-code-blocks'], )
     obj.testname = markdown2.markdown(self.convert_markdown_split_line(obj.testname), extras=['fenced-code-blocks'], )
     #obj.question = markdown2.markdown(self.convert_markdown_split_line(obj.question), extras=['fenced-code-blocks'], )
     #obj.assumption = markdown2.markdown(self.convert_markdown_split_line(obj.assumption), extras=['fenced-code-blocks'], )
     return obj  
示例#12
0
文件: main.py 项目: voidcode/howtoapp
def loadCourse(coursefilename):
	currentSelectedCourse = coursename
	tmp=''
	with open(coursesRoot + coursefilename, 'r') as data:
		tmp = data.read()
	#print htmlStartString+markdown2.markdown(tmp)+htmlEndString
	wv.load_html_string(htmlStartString+markdown2.markdown(tmp)+htmlEndString, "file:///")
	print htmlStartString+markdown2.markdown(tmp)+htmlEndString
示例#13
0
def info(job_id, slug=None):
    job = Job.query.filter(Job.id == job_id).first_or_404()
    job.nb_viewed += 1
    job.save()

    # convert markdown to html
    job_description, job_motivation = markdown2.markdown(job.description), markdown2.markdown(job.motivation)
    return render_template('jobs/job.html', job=job, html_description=job_description, html_motivation=job_motivation)
示例#14
0
文件: common.py 项目: drguildo/bloggy
def print_post(title, body, date=None):
    """Formats and prints a post"""
    print '<div class="blogpost">'
    print '<h1>%s</h1>' % title
    if date:
        print '<h3>%s</h3>' % time.ctime(date)
    print markdown2.markdown(body)
    print '</div>'
示例#15
0
def md2(value):
    '''
        目前markdown2 无法处理井号(####)标题
    '''
    return mark_safe(markdown2.markdown(
                force_unicode(value),
                safe_mode=True)
            )
    return mark_safe(markdown2.markdown(value))
示例#16
0
 def gen_html(self):
     import markdown2
     mkd = self.parse()
     if self.pyg:
         logger.debug("Parser.gen_html() codehilite\n mkd:%s" % (mkd,))
         return markdown2.markdown(mkd, extras={'code-color': None})
     else:
         logger.debug("Parser.gen_html()\n mkd:%s" % (mkd,))
         return markdown2.markdown(mkd)
示例#17
0
文件: mtext.py 项目: nive/cms-modules
 def OnCommit(self, **kw):
     if self.useCache:
         self.data["tcache"] = markdown2.markdown(self.data.get("textblock"))
         text = ConvertHTMLToText(self.data["tcache"], removeReST=True)
     else:
         temp = markdown2.markdown(self.data.get("textblock"))
         text = ConvertHTMLToText(temp, removeReST=True)
     self.meta["title"] = CutText(text, self.titleLen, postfix=u"")
     return True
示例#18
0
def md(value, arg=None):
    try:
        if not arg:
            return mark_safe(markdown(value))
        else:
            mded =  markdown(value)
            rep = '<p class="%s">'%(arg)
            return mark_safe(mded.replace('<p>', rep))
    except Exception:
        return value
示例#19
0
async def get_blog(id):
    blog = await Blog.find(id)
    comments = await Comment.findAll('blog_id=?', [id], orderBy='created_at desc')
    for c in comments:
        c.html_content = markdown(c.content)
    blog.html_content = markdown(blog.content)
    return {
        '__template__': 'blog.html',
        'blog': blog,
        'comments': comments
    }
示例#20
0
文件: models.py 项目: bougie/pybrief
    def clean(self):
        try:
            if markdown is not None:
                extras = ['fenced-code-blocks']
                self.content_html = markdown(self.content, extras=extras)
                self.description_html = markdown(wrap_description(self.content),
                                                 extras=extras)
        except:
            raise self.ValidationError("Player42, try again")

        super(Post, self).clean()
示例#21
0
文件: db.py 项目: Lwxiang/CoFun
 def Get(problemid, Markdown=True):
     res = db.select("Problem", where="ProblemID="+str(problemid))
     if not res:
         return None
     res = list(res)[0]
     if Markdown:
         res.ProblemDescription = markdown2.markdown(res.ProblemDescription)
         res.ProblemInput = markdown2.markdown(res.ProblemInput)
         res.ProblemOutput = markdown2.markdown(res.ProblemOutput)
         res.ProblemHint = markdown2.markdown(res.ProblemHint)
     return res
示例#22
0
    def render(self, this, template_name, **kwargs):
        if 'post' in kwargs:
            kwargs['post'].text = markdown2.markdown( kwargs['post'].text )

        elif 'page' in kwargs:
            kwargs['page'].text = markdown2.markdown( kwargs['page'].text )
        return {
            'this' : this ,
            'template_name' : template_name ,
            'kwargs' : kwargs
        }
示例#23
0
 def get_object(self, queryset=None):
     obj = super(GroomingDetailView, self).get_object()
     obj.scope = markdown2.markdown(self.convert_markdown_split_line(obj.scope), extras=['fenced-code-blocks'], )
     obj.question = markdown2.markdown(self.convert_markdown_split_line(obj.question), extras=['fenced-code-blocks'], )
     obj.assumption = markdown2.markdown(self.convert_markdown_split_line(obj.assumption), extras=['fenced-code-blocks'], )
     obj.content = markdown2.markdown(self.convert_markdown_split_line(obj.content), extras=['fenced-code-blocks'],)
     #obj.atdd = obj.atddcase_set.all()
     #obj.atdd = []
     #for atdd in obj.atddcase_set.all():
     #    obj.atdd.append(atdd.suitename)
     return obj  
示例#24
0
 def save(self, force_insert=False, force_update=False):
     self.body_html = markdown(self.body)
     if self.excerpt:
         self.excerpt_html = markdown(self.excerpt)
         
     # It's better to save this formatting once and save RAM by using more disc
     
     self.year = int(self.pub_date.strftime("%Y"))
     self.month = self.pub_date.strftime("%b").lower()
     self.day =  int(self.pub_date.strftime("%d"))
     
     super(Entry, self).save(force_insert, force_update)
示例#25
0
 def save(self, force_insert=False, force_update=False):
     splitted_url = self.link.split("/")
     youtube_video_id = splitted_url[-1]
     self.thumb_url = YOUTUBE_IMAGE_URL + youtube_video_id + "/default.jpg"
     
     
     self.embed_url = "http://www.youtube.com/embed/" + youtube_video_id
     self.description_html = markdown(self.description)
     if self.excerpt:
         self.excerpt_html = markdown(self.excerpt)
         
     super(Video, self).save(force_insert, force_update)
示例#26
0
文件: views.py 项目: phenomeno/dblog
def detail(request, post_id, slug=None):
    post = get_object_or_404(Post, pk=post_id)
    split_body = post.post_body.split("]", 1)
    split_body = [n.strip() for n in split_body]
    if len(split_body) > 1:
        img_list = ast.literal_eval(split_body[0]+"]")
        post.post_body = markdown(split_body[1], extras=["fenced-code-blocks"])
    else:
        img_list = []
        post.post_body = markdown(split_body[0], extras=["fenced-code-blocks"])
    post.image_urls = img_list
    return render(request, 'posts/detail.html', {'post': post})
示例#27
0
def generate_index(srcfn, tgtfn):
    with open(srcfn) as f:
        index = f.read()
    index = index.split("\n\n")
    bullet0 = markdown2.markdown(index[0], extras=extras)
    bullet1 = markdown2.markdown(index[1], extras=extras)
    bullet2 = markdown2.markdown(index[2], extras=extras)
    bullet3 = markdown2.markdown("\n\n".join(index[3:]), extras=extras)
    doc = string.Template(TEMPLATE_INDEX).safe_substitute(
        bullet0=bullet0, bullet1=bullet1, bullet2=bullet2, bullet3=bullet3,
        date=generated)
    with open(tgtfn, "w") as f:
        f.write(doc)
示例#28
0
文件: views.py 项目: synopslive/deck
def export_current_episode(request):
    cached = redis_instance.get('deck_current_episode_cache')

    if not cached:
        with redis_instance.lock('deck_current_episode_lock'):
            cached = redis_instance.get('deck_current_episode_cache')

            if not cached:
                episodes = Episode.objects.filter(shown=True) \
                    .filter(end_time__gte=datetime.now()) \
                    .select_related('show') \
                    .order_by("time")

                response = {}

                if episodes.count() > 0:
                    episode = episodes[0]
                    response = {
                        'id': episode.id,
                        'bg_image': episode.auto_livepage_bg_image.url,
                        'show_name': episode.show.name,
                        'show_slug': episode.show.slug,
                        'twitter_button_label': episode.show.twitter_button_label,
                        'twitter_button_message': episode.show.twitter_button_message,
                        'twitter_widget': episode.show.twitter_widget,
                        'number': episode.number,
                        'content': markdown2.markdown(force_unicode(episode.content)),
                        'copyright': markdown2.markdown(force_unicode(episode.show.copyright)),
                        'time': episode.time.isoformat(),
                        'end_time': episode.end_time.isoformat()
                    }

                prog = re.compile(r'^mount=.+?, artist=(?P<artist>.*?), title=(?P<title>.*?), listeners=(?P<listeners>.*?)$')

                try:
                    hosts = LIVE_HOSTS[:]
                    random.shuffle(hosts)
                    content = urllib2.urlopen("http://{}/status4.xsl".format(hosts[0]), timeout=2).readlines()
                    interesting_line = [prog.match(line) for line in content if line.startswith("mount=/synopslive-permanent.ogg")][0]

                    response["artist"] = interesting_line.group("artist")
                    response["title"] = interesting_line.group("title")
                except Exception:
                    pass

                cached = json.dumps(response)

                redis_instance.set("deck_current_episode_cache", cached)
                redis_instance.expire("deck_current_episode_cache", 10)

    return HttpResponse(cached, content_type="application/json")
示例#29
0
文件: db.py 项目: Lwxiang/CoFun
 def GetProblem(cid, pid):
     contest = db.select("Contest", where="ContestID="+str(cid))
     prob = db.select("ContestProblem, Problem", what="Problem.*", where="ContestProblem.ContestID="+str(cid)+" AND Problem.ProblemID=ContestProblem.ProblemID AND Problem.ProblemID="+str(pid))
     if not contest or not prob:
         return (None, None)
     else:
         contest = list(contest)[0]
         contest.ContestDescription = markdown2.markdown(contest.ContestDescription)
         prob = list(prob)[0]
         prob.ProblemDescription = markdown2.markdown(prob.ProblemDescription)
         prob.ProblemInput = markdown2.markdown(prob.ProblemInput)
         prob.ProblemOutput = markdown2.markdown(prob.ProblemOutput)
         prob.ProblemHint = markdown2.markdown(prob.ProblemHint)
         return (contest, prob)
示例#30
0
def get_markdown():
    import markdown2
    doc_name = request.form['docName']
    try:
        with open('/var/www/public/templates/docs/' + doc_name + '.md', 'r') as mdf:
            return markdown2.markdown(mdf.read())
    except:
        try:
            with open('/var/www/public/templates/' + doc_name + '.md', 'r') as mdf:
                return markdown2.markdown(mdf.read())
        except:
            with open('/var/www/public/templates/docs/default.md', 'r') as mdf:
                return markdown2.markdown(mdf.read())
    return 'Internal server error', 500
示例#31
0
 def markdown_content(self):
     return markdown2.markdown(self.content)
示例#32
0
import PIL
from PIL import Image
import markdown2
from os import listdir
from os.path import isfile, join

mypath = "../text_main/"
mypath_out = "../../birds/main/"
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for f in onlyfiles:
	if ".md" in f:
		fi = open(mypath+f, "rU")
		data=fi.read()
		fi.close()
		web_text = markdown2.markdown(data)
		web_text = web_text.replace(u"\u2018", "'").replace(u"\u2019", "'").replace(u"\u201c",'"').replace(u"\u201d", '"').replace(u'\u2014',"--").replace(u'\xef',"'")
		web_text = web_text.replace(u'\xbd',"1/2")
		outfile = f.replace(".md","")
		outfile = outfile.upper() + ".html"
		fi = open(mypath_out+outfile, "w")
		fi.write(web_text)
		fi.close()



audio_text = '''
				<div id="audio">
					<audio controls <?php if($autoplay==$number){echo 'autoplay';}?> >
						<?php $song = "birdsong/".$key_array[$page][$number].".mp3"; ?>
					    <source src="<?php echo $song; ?>" type="audio/mpeg">
						Your browser does not support the audio element.
示例#33
0
文件: views.py 项目: kmunge/blog
def single_post(id):
    post = Post.query.get(id)
    if post is None:
        abort(404)
    format_post = markdown2.markdown(post.post,extras=["code-friendly", "fenced-code-blocks"])
    return render_template('post.html',post = post,format_post=format_post)
示例#34
0
def sendmail(recipients=[],
             sender="",
             subject="No Subject",
             message="No Message",
             as_markdown=False,
             delayed=True,
             reference_doctype=None,
             reference_name=None,
             unsubscribe_method=None,
             unsubscribe_params=None,
             unsubscribe_message=None,
             attachments=None,
             content=None,
             doctype=None,
             name=None,
             reply_to=None,
             cc=[],
             message_id=None,
             in_reply_to=None,
             send_after=None,
             expose_recipients=None,
             send_priority=1,
             communication=None,
             retry=1,
             now=None,
             read_receipt=None,
             is_notification=False,
             inline_images=None,
             template=None,
             args=None,
             header=None):
    """Send email using user's default **Email Account** or global default **Email Account**.


	:param recipients: List of recipients.
	:param sender: Email sender. Default is current user.
	:param subject: Email Subject.
	:param message: (or `content`) Email Content.
	:param as_markdown: Convert content markdown to HTML.
	:param delayed: Send via scheduled email sender **Email Queue**. Don't send immediately. Default is true
	:param send_priority: Priority for Email Queue, default 1.
	:param reference_doctype: (or `doctype`) Append as communication to this DocType.
	:param reference_name: (or `name`) Append as communication to this document name.
	:param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe`
	:param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict).
	:param attachments: List of attachments.
	:param reply_to: Reply-To Email Address.
	:param message_id: Used for threading. If a reply is received to this email, Message-Id is sent back as In-Reply-To in received email.
	:param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To.
	:param send_after: Send after the given datetime.
	:param expose_recipients: Display all recipients in the footer message - "This email was sent to"
	:param communication: Communication link to be set in Email Queue record
	:param inline_images: List of inline images as {"filename", "filecontent"}. All src properties will be replaced with random Content-Id
	:param template: Name of html template from templates/emails folder
	:param args: Arguments for rendering the template
	:param header: Append header in email
	"""

    text_content = None
    if template:
        message, text_content = get_email_from_template(template, args)

    message = content or message

    if as_markdown:
        from markdown2 import markdown
        message = markdown(message)

    if not delayed:
        now = True

    import email.queue
    email.queue.send(recipients=recipients,
                     sender=sender,
                     subject=subject,
                     message=message,
                     text_content=text_content,
                     reference_doctype=doctype or reference_doctype,
                     reference_name=name or reference_name,
                     unsubscribe_method=unsubscribe_method,
                     unsubscribe_params=unsubscribe_params,
                     unsubscribe_message=unsubscribe_message,
                     attachments=attachments,
                     reply_to=reply_to,
                     cc=cc,
                     message_id=message_id,
                     in_reply_to=in_reply_to,
                     send_after=send_after,
                     expose_recipients=expose_recipients,
                     send_priority=send_priority,
                     communication=communication,
                     now=now,
                     read_receipt=read_receipt,
                     is_notification=is_notification,
                     inline_images=inline_images,
                     header=header)
示例#35
0
文件: views.py 项目: chaudhryna/wiki
def entry_detail(request, title):
    content = markdown2.markdown(util.get_entry(title))
    request.session['title'] = title
    return render(request, "encyclopedia/entry_detail.html", {
        "content": content
    })
示例#36
0
    def run(self, edit, target='browser'):
        region = sublime.Region(0, self.view.size())
        encoding = self.view.encoding()
        if encoding == 'Undefined':
            encoding = 'utf-8'
        elif encoding == 'Western (Windows 1252)':
            encoding = 'windows-1252'
        contents = self.view.substr(region)

        # convert the markdown
        markdown_html = markdown2.markdown(contents,
                                           extras=[
                                               'footnotes', 'toc',
                                               'fenced-code-blocks',
                                               'cuddled-lists', 'code-friendly'
                                           ])

        # postprocess the html
        markdown_html = self.postprocessor(markdown_html)

        # check if LiveReload ST2 extension installed
        livereload_installed = ('LiveReload'
                                in os.listdir(sublime.packages_path()))

        # build the html
        html_contents = u'<!DOCTYPE html>'
        html_contents += '<html><head><meta charset="%s">' % encoding
        styles = self.getCSS()
        html_contents += '<style>%s</style>' % styles
        if livereload_installed:
            html_contents += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>'
        html_contents += '</head><body>'
        html_contents += markdown_html
        html_contents += '</body>'

        if target in ['disk', 'browser']:
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            tmp_html = open(tmp_fullpath, 'w')
            tmp_html.write(html_contents.encode(encoding))
            tmp_html.close()
            # todo : livereload ?
            if target == 'browser':
                config_browser = settings.get('browser')
                if config_browser != 'default':
                    cmd = '"%s" %s' % (config_browser, tmp_fullpath)
                    if sys.platform == 'darwin':
                        cmd = "open -a %s" % cmd
                    print "Markdown Preview: executing", cmd
                    result = os.system(cmd)
                    if result != 0:
                        sublime.error_message(
                            'cannot execute "%s" Please check your Markdown Preview settings'
                            % config_browser)
                    else:
                        sublime.status_message(
                            'Markdown preview launched in %s' % config_browser)
                else:
                    desktop.open(tmp_fullpath)
                    sublime.status_message(
                        'Markdown preview launched in default html viewer')
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, html_contents)
            new_view.end_edit(new_edit)
            sublime.status_message('Markdown preview launched in sublime')
示例#37
0
 def rendered(self):
     return markdown2.markdown(self.content)
示例#38
0
def sendmail(recipients=[],
             sender="",
             subject="No Subject",
             message="No Message",
             as_markdown=False,
             delayed=True,
             reference_doctype=None,
             reference_name=None,
             unsubscribe_method=None,
             unsubscribe_params=None,
             unsubscribe_message=None,
             attachments=None,
             content=None,
             doctype=None,
             name=None,
             reply_to=None,
             cc=[],
             message_id=None,
             in_reply_to=None,
             send_after=None,
             expose_recipients=None,
             send_priority=1,
             communication=None,
             retry=1,
             now=None):
    """Send email using user's default **Email Account** or global default **Email Account**.


	:param recipients: List of recipients.
	:param sender: Email sender. Default is current user.
	:param subject: Email Subject.
	:param message: (or `content`) Email Content.
	:param as_markdown: Convert content markdown to HTML.
	:param delayed: Send via scheduled email sender **Email Queue**. Don't send immediately. Default is true
	:param send_priority: Priority for Email Queue, default 1.
	:param reference_doctype: (or `doctype`) Append as communication to this DocType.
	:param reference_name: (or `name`) Append as communication to this document name.
	:param unsubscribe_method: Unsubscribe url with options email, doctype, name. e.g. `/api/method/unsubscribe`
	:param unsubscribe_params: Unsubscribe paramaters to be loaded on the unsubscribe_method [optional] (dict).
	:param attachments: List of attachments.
	:param reply_to: Reply-To email id.
	:param message_id: Used for threading. If a reply is received to this email, Message-Id is sent back as In-Reply-To in received email.
	:param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To.
	:param send_after: Send after the given datetime.
	:param expose_recipients: Display all recipients in the footer message - "This email was sent to"
	:param communication: Communication link to be set in Email Queue record
	"""
    message = content or message

    if as_markdown:
        from markdown2 import markdown
        message = markdown(message)

    if not delayed:
        now = True

    import email.queue
    email.queue.send(recipients=recipients,
                     sender=sender,
                     subject=subject,
                     message=message,
                     reference_doctype=doctype or reference_doctype,
                     reference_name=name or reference_name,
                     unsubscribe_method=unsubscribe_method,
                     unsubscribe_params=unsubscribe_params,
                     unsubscribe_message=unsubscribe_message,
                     attachments=attachments,
                     reply_to=reply_to,
                     cc=cc,
                     message_id=message_id,
                     in_reply_to=in_reply_to,
                     send_after=send_after,
                     expose_recipients=expose_recipients,
                     send_priority=send_priority,
                     communication=communication,
                     now=now)
示例#39
0
    def markdown_filter(self, markdown_text):
        """
            Convert a markdown text into a ODT formated text
        """

        if not isinstance(markdown_text, basestring):
            return ''

        from xml.dom import Node
        from markdown_map import transform_map

        try:
            from markdown2 import markdown
        except ImportError:
            raise SecretaryError('Could not import markdown2 library. Install it using "pip install markdown2"')

        styles_cache = {}   # cache styles searching
        html_text = markdown(markdown_text)
        xml_object = parseString('<html>%s</html>' % html_text.encode('ascii', 'xmlcharrefreplace'))

        # Transform HTML tags as specified in transform_map
        # Some tags may require extra attributes in ODT.
        # Additional attributes are indicated in the 'attributes' property

        for tag in transform_map:
            html_nodes = xml_object.getElementsByTagName(tag)
            for html_node in html_nodes:
                odt_node = xml_object.createElement(transform_map[tag]['replace_with'])

                # Transfer child nodes
                if html_node.hasChildNodes():
                    for child_node in html_node.childNodes:
                        odt_node.appendChild(child_node.cloneNode(True))

                # Add style-attributes defined in transform_map
                if 'style_attributes' in transform_map[tag]:
                    for k, v in transform_map[tag]['style_attributes'].items():
                        odt_node.setAttribute('text:%s' % k, v)

                # Add defined attributes
                if 'attributes' in transform_map[tag]:
                    for k, v in transform_map[tag]['attributes'].items():
                        odt_node.setAttribute(k, v)

                    # copy original href attribute in <a> tag
                    if tag == 'a':
                        if html_node.hasAttribute('href'):
                            odt_node.setAttribute('xlink:href',
                                html_node.getAttribute('href'))

                # Does the node need to create an style?
                if 'style' in transform_map[tag]:
                    name = transform_map[tag]['style']['name']
                    if not name in styles_cache:
                        style_node = self.get_style_by_name(name)

                        if style_node is None:
                            # Create and cache the style node
                            style_node = self.insert_style_in_content(
                                name, transform_map[tag]['style'].get('attributes', None),
                                **transform_map[tag]['style']['properties'])
                            styles_cache[name] = style_node

                html_node.parentNode.replaceChild(odt_node, html_node)

        def node_to_string(node):
            result = node.toxml()

            # linebreaks in preformated nodes should be converted to <text:line-break/>
            if (node.__class__.__name__ != 'Text') and \
                (node.getAttribute('text:style-name') == 'Preformatted_20_Text'):
                result = result.replace('\n', '<text:line-break/>')

            # All double linebreak should be replaced with an empty paragraph
            return result.replace('\n\n', '<text:p text:style-name="Standard"/>')


        return ''.join(node_as_str for node_as_str in map(node_to_string,
                xml_object.getElementsByTagName('html')[0].childNodes))
示例#40
0
 def get_queryset(self):
     article_list = Article.objects.filter(created_time__year=self.kwargs['year'],created_time__month=self.kwargs['month'], status='p')
     for article in article_list:
         article.body = markdown2.markdown(article.body, extras=['fenced-code-blocks'], )
     return article_list
示例#41
0
 def get_queryset(self):
     article_list = Article.objects.filter(tags=self.kwargs['tag_id'], status='p')
     for article in article_list:
         article.body = markdown2.markdown(article.body, extras=['fenced-code-blocks'],)
     return article_list
示例#42
0
 def get_queryset(self):
     article_list = Article.objects.filter(category=self.kwargs['cate_id'])
     for article in article_list:
         article.body = markdown2.markdown(article.body,extras=['fenced-code-blocks'])
     return article_list
示例#43
0
 def html(self):
     return markdown2.markdown(self.body)
示例#44
0
 def render(self, text):
     html = markdown2.markdown(text)
     print html
     return self.render_string("modules/bio.html", html=html)
示例#45
0
文件: wasa2il.py 项目: gyfu/wasa2il
def markdown(value):
    return mark_safe(markdown2.markdown(value, safe_mode='escape'))
示例#46
0
def markdown_filter(text):
    text = markdown2.markdown(text, extras=settings.MARKDOWN_FILTER_EXTRAS)
    html = bleach.clean(text, tags=settings.MARKDOWN_FILTER_WHITELIST_TAGS)
    return bleach.linkify(html)
示例#47
0
 def get(self, slug):
     posts = self.session.query('SELECT * FROM post WHERE slug = %(slug)s',
                                {'slug': slug})
     html = markdown2.markdown(posts[0]['body'])
     context = {'post': posts[0], 'html': html}
     self.render_template("post.html", context)
示例#48
0
 def html_item(self):
     self.finding['steps_to_reproduce'] = self.html_steps_to_reproduce()
     return markdown2.markdown(self.__str__(), extras=["tables"])
示例#49
0
def md_to_html(md_str):
    return markdown2.markdown(md_str)
示例#50
0
def parse(text):
    html = markdown2.markdown(text)
    html = html.encode('ascii', 'replace')
    return html
 </HTML>"""

sampleRallyHTML = """
<u>Acceptance Criteria</u>
<div>
  <ul>
    <li>A tag is added on successful build in TC.</li>
    <li>TC only monitors the master branch.</li>
    <li>TC creates a new build for every commit.</li>
    <li>All release/dev branches are merged into master.</li>
  </ul>
</div>"""

anotherSampleRallyHTML = """
When a vin is entered that is not valid, the following exception can be seen in the error logs. This does not affect the customer but does affect logging.<br /><div>        <p class="p1"><span class="s1">[2015-05-27 11:54:34,070] DEBUG [catalina-exec-11] com.himex.restsupport.db.DBConnectionLookup - DB Connection closed by com.himex.inthub.controllers.commondata.services.CommonDataService.validateVIN(CommonDataService.java:269)</span></p> <p class="p1"><span class="s1">[2015-05-27 11:54:34,073] ERROR [catalina-exec-11] com.himex.inthub.controllers.commondata.objects.ResultsLogger - Error [{}]</span></p> <p class="p1"><span class="s1">java.lang.NullPointerException</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at com.himex.inthub.controllers.commondata.objects.ResultsLogger.log(ResultsLogger.java:29) [ResultsLogger.class:?]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at com.himex.inthub.controllers.commondata.services.CommonDataService.compatCheck(CommonDataService.java:227) [CommonDataService.class:?]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at com.himex.inthub.controllers.commondata.services.CommonDataService.check(CommonDataService.java:96) [CommonDataService.class:?]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at com.himex.inthub.soap.cd.CompatDBImpl.checkVIN(CompatDBImpl.java:76) [CompatDBImpl.class:?]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at com.himex.inthub.soap.cd.endpoint.CheckVINEndpoint.checkVINRequest(CheckVINEndpoint.java:32) [CheckVINEndpoint.class:?]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at sun.reflect.GeneratedMethodAccessor67.invoke(Unknown Source) ~[?:?]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_65]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_65]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at org.springframework.ws.server.endpoint.MethodEndpoint.invoke(MethodEndpoint.java:132) [spring-ws-2.1.0.RELEASE-all.jar:2.1.0.RELEASE]</span></p> <p class="p1"><span class="s1">&nbsp; &nbsp; &nbsp; &nbsp;at</span></p></div>
"""

print "\nOriginal HTML\n{}".format(anotherSampleRallyHTML)

toMarkdown = html2text.html2text(anotherSampleRallyHTML)
print "\nHTML to Markdown\n{}".format(toMarkdown)

toHTML = markdown2.markdown(toMarkdown)
print "\nMarkdown to HTML\n{}".format(toHTML)

backToMarkdown = html2text.html2text(toHTML)
print "\nHTML back to Markdown\n{}".format(backToMarkdown)
"""
 So HTML to Markdown is easy but changing back needs some work

"""
示例#52
0
 def get_comments(self, comments):
     for comment in comments:
         comment["comments"] = self.get_comments(comment["comments"]) if comment.get("comment_ids") else []
         comment["content"] = markdown2.markdown(comment["content"], safe_mode=True)
     return comments
示例#53
0
文件: feeds.py 项目: luoyi2017/July
 def item_description(self, item):
     return markdown(item.abstract)
示例#54
0
import os
from datetime import datetime
from jinja2 import Environment, PackageLoader
from markdown2 import markdown
from minify import minify

POSTS = {}

for markdown_post in os.listdir('content'):
    file_path = os.path.join('content', markdown_post)

    with open(file_path, 'r') as file:
        POSTS[markdown_post] = markdown(file.read(), extras=['metadata'])

POSTS = {
    post: POSTS[post]
    for post in sorted(POSTS,
                       key=lambda post: datetime.strptime(
                           POSTS[post].metadata['date'], '%Y-%m-%d'),
                       reverse=True)
}

env = Environment(loader=PackageLoader('main', 'templates'))
home_template = env.get_template('home.html')
post_template = env.get_template('post.html')

posts_metadata = [POSTS[post].metadata for post in POSTS]
tags = [post['tags'] for post in posts_metadata]
home_html = home_template.render(posts=posts_metadata, tags=tags)

output = os.path.join(os.getcwd(), 'output\\home.html')
示例#55
0
文件: views.py 项目: kmunge/blog
def single_comment(id):
    comment = Comment.query.get(id)
    if comment is None:
        abort(404)
    format_comment = markdown2.markdown(comment.comment,extras=["code-friendly", "fenced-code-blocks"])
    return render_template('comment.html',comment = comment,format_comment=format_comment)
示例#56
0
def markdown_to_html(markdown_text):
    """ Convierte text en HTML """
    html_body = markdown2.markdown(markdown_text)
    return mark_safe(html_body)
示例#57
0
    def help_about(self):

        message = read_file(":/about.md").format(self.Info.version, self.Info.date)
        html = markdown2.markdown(str(message))

        QMessageBox.about(self, "About %s"%NAME, html)
示例#58
0
 def get_queryset(self):
     article_list = Article.objects.all()
     for article in article_list:
         article.body = markdown2.markdown(article.body,extras=['fenced-code-blocks'])
     return article_list
示例#59
0
 def get_object(self):
     obj = super(ArticleDetailView, self).get_object()
     obj.body = markdown2.markdown(obj.body, extras=['fenced-code-blocks'], )
     return obj
示例#60
0
 def digest_html(self, size=140):
     return markdown2.markdown(self.digest(size))