• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python template.render函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中template.render函数的典型用法代码示例。如果您正苦于以下问题:Python render函数的具体用法?Python render怎么用?Python render使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了render函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: login_post

def login_post():
	page = Page('/login', 'Login')
	current_user = process_cookie(request.get_cookie("login"))
	
	if current_user is not None:
		return template.render("home_redirect.html",
							   {'message': "<h1>You are already logged in</h1>"})

	if request.forms.get('username') == 'admin' and\
			user.hash_password(request.forms.get('password')) == config["admin_hash"]:
		response.set_cookie("login",
							cookies.give_cookie("admin"),
							max_age=cookies.expire_time)
		
		return template.render("vote_count_redirect.html",
							   {'message': "<h1>Admin Login Successful</h1>"})
	
	validity = user.is_valid_login(request.forms.get('username'),
								   request.forms.get('password'))
	
	if validity == 0: # Success		
		cookie = cookies.give_cookie(request.forms.get('username'))
		print cookie
		response.set_cookie("login", cookie, max_age=cookies.expire_time)
		return template.render("home_redirect.html",
							   {'message': "<h1>Login Successful</h1>"})
	else:
		return template.render("login.html", {'config': config,
											  'pages': pages, 'page': page,
											  'valid': validity,
											  'user': current_user})
开发者ID:DpEpsilon,项目名称:NBHS-Voting-Site,代码行数:31,代码来源:main.py


示例2: vote_post

def vote_post():
	page = Page('/vote', 'Vote')
	if page not in pages:
		abort(404)
	current_user = process_cookie(request.get_cookie("login"))
	given_csrf_key = request.forms.get('csrf')

	if not csrf.check_csrf_key(current_user.userid, given_csrf_key):
		abort(403, "A potential CSRF attack was detected. "
			  "Please try again later.")
	
	if current_user is None:
		redirect('/login?message=3')
	if current_user.has_voted:
		return template.render("home_redirect.html",
							   {'message': "<h1>You have already voted.</h1>"})
	
	nominees = user.get_nominees()
	votes = []
	for n in nominees:
		if request.forms.get(str(n.userid)):
			votes.append(n.userid)
	
	if len(votes) > config['num_votes']:
		redirect('/vote')

	submissions.submit_votes(current_user.userid, votes)
		
	return template.render("home_redirect.html",
						   {'message': "<h1>Vote successful.</h1>"})
开发者ID:DpEpsilon,项目名称:NBHS-Voting-Site,代码行数:30,代码来源:main.py


示例3: nominate_get

def nominate_get():
	page = Page('/nominate', 'Nominate')
	if page not in pages:
		abort(404)
	current_user = process_cookie(request.get_cookie("login"))
	nominee_fields = config['nominee_fields']
	
	if current_user is None:
		redirect('/login?message=3')
	
	if current_user.student_info is None:
		return template.render("home_redirect.html",
							   {'message': "<h1>Staff cannot nominate</h1>"})
	if not current_user.student_info.is_nominee and config['prenominate']:
		return template.render("home_redirect.html",
							   {'message': "<h1>You are not a candidate.</h1>"})
	
	nominee_fields = filter(
		lambda x: x['name'] not in current_user.student_info.nominee_fields,
		nominee_fields)

	if len(nominee_fields) == 0:
		return template.render("home_redirect.html",
							   {'message': """<h1>You have already
 submitted your nomination</h1>"""})
	
	return template.render("nominate.html",
						   {'config': config,
							'nominee_fields': nominee_fields,
							'csrf': csrf.get_csrf_key(current_user.userid),
							'pages': pages, 'page': page,
							'user': current_user})
开发者ID:DpEpsilon,项目名称:NBHS-Voting-Site,代码行数:32,代码来源:main.py


示例4: add_package

def add_package(dir, context, package, alternate_template=None):
	name = package['name'].lower().replace('-','_')
	package['name'] = name
	bosh('generate', 'package', name)
	target_dir = os.path.realpath(os.path.join(dir, name))
	package_dir = os.path.realpath(os.path.join('packages', name))
	mkdir_p(target_dir)
	template_dir = 'packages'
	if alternate_template is not None:
		template_dir = os.path.join(template_dir, alternate_template)
	package_context = {
		'context': context,
		'package': package,
		'files': []
	}
	with cd('..'):
		for file in package.get('files', []):
			filename = file.get('name', os.path.basename(file['path']))
			try:
				urllib.urlretrieve(file['path'], os.path.join(target_dir, filename))
			except ValueError: # Invalid URL, assume filename
				shutil.copy(os.path.join('..', file['path']), target_dir)
			package_context['files'] += [ filename ]
			file['name'] = filename
	template.render(
		os.path.join(package_dir, 'spec'),
		os.path.join(template_dir, 'spec'),
		package_context
	)
	template.render(
		os.path.join(package_dir, 'packaging'),
		os.path.join(template_dir, 'packaging'),
		package_context
	)
开发者ID:tarsam2009,项目名称:tile-generator,代码行数:34,代码来源:build.py


示例5: vote_get

def vote_get():
	page = Page('/vote', 'Vote')
	if page not in pages:
		abort(404)
	current_user = process_cookie(request.get_cookie("login"))

	if current_user is None:
		redirect('/login?message=3')
	if current_user.has_voted:
		return template.render("home_redirect.html",
							   {'message': "<h1>You have already voted.</h1>"})
	
	nominees = user.get_nominees()
	random.shuffle(nominees)
	col_size = len(nominees)/3
	if len(nominees) % 3 > 0:
		col_size += 1
	
	nominees = [nominees[:col_size],
				nominees[col_size:2*col_size],
				nominees[2*col_size:]]
	
	return template.render("voting.html",
						   {'config': config,
							'pages': pages, 'page': page,
							'nominees': nominees,
							'csrf': csrf.get_csrf_key(current_user.userid),
							'user': current_user})
开发者ID:DpEpsilon,项目名称:NBHS-Voting-Site,代码行数:28,代码来源:main.py


示例6: add_bosh_job

def add_bosh_job(context, package, job_type, post_deploy=False, pre_delete=False):
	job_name = job_type + '-' + package['name']
	bosh('generate', 'job', job_name)
	job_context = {
		'job_name': job_name,
		'job_type': job_type,
		'context': context,
		'package': package,
	}
	template.render(
		os.path.join('jobs', job_name, 'spec'),
		os.path.join('jobs', 'spec'),
		job_context
	)
	template.render(
		os.path.join('jobs', job_name, 'templates', job_name + '.sh.erb'),
		os.path.join('jobs', job_type + '.sh.erb'),
		job_context
	)
	context['jobs'] = context.get('jobs', []) + [{
		'name': job_name,
		'type': job_type,
		'package': package,
	}]
	if post_deploy:
		context['post_deploy_errands'] = context.get('post_deploy_errands', []) + [{ 'name': job_name }]
	if pre_delete:
		context['pre_delete_errands'] = context.get('pre_delete_errands', []) + [{ 'name': job_name }]
开发者ID:tarsam2009,项目名称:tile-generator,代码行数:28,代码来源:build.py


示例7: create_tile

def create_tile(context):
	release = context['release']
	release['file'] = os.path.basename(release['tarball'])
	with cd('releases'):
		print 'tile import release', release['name']
		shutil.copy(release['tarball'], release['file'])
		if context.get('requires_docker_bosh', False):
			print 'tile import release docker'
			docker_release = download_docker_release()
			context['docker_release'] = docker_release
	print 'tile generate metadata'
	template.render('metadata/' + release['name'] + '.yml', 'tile/metadata.yml', context)
	print 'tile generate content-migrations'
	template.render('content_migrations/' + release['name'] + '.yml', 'tile/content-migrations.yml', context)
	print 'tile generate package'
	pivotal_file = release['name'] + '-' + release['version'] + '.pivotal'
	with zipfile.ZipFile(pivotal_file, 'w') as f:
		f.write(os.path.join('releases', release['file']))
		if context.get('requires_docker_bosh', False):
			docker_release = context['docker_release']
			f.write(os.path.join('releases', docker_release['file']))
		f.write(os.path.join('metadata', release['name'] + '.yml'))
		f.write(os.path.join('content_migrations', release['name'] + '.yml'))
	print
	print 'created tile', pivotal_file
开发者ID:Dwaligon,项目名称:tile-generator,代码行数:25,代码来源:build.py


示例8: add_package

def add_package(dir, context, package, alternate_template=None):
	name = package['name'].lower().replace('-','_')
	package['name'] = name
	bosh('generate', 'package', name)
	target_dir = os.path.realpath(os.path.join(dir, name))
	package_dir = os.path.realpath(os.path.join('packages', name))
	mkdir_p(target_dir)
	template_dir = 'packages'
	if alternate_template is not None:
		template_dir = os.path.join(template_dir, alternate_template)
	package_context = {
		'context': context,
		'package': package,
		'files': []
	}
	with cd('..'):
		files = package.get('files', [])
		path = package.get('path', None)
		if path is not None:
			files += [ { 'path': path } ]
			package['path'] = os.path.basename(path)
		manifest = package.get('manifest', None)
		manifest_path = None
		if type(manifest) is dict:
			manifest_path = manifest.get('path', None)
		if manifest_path is not None:
			files += [ { 'path': manifest_path } ]
			package['manifest']['path'] = os.path.basename(manifest_path)
		for file in files:
			filename = file.get('name', os.path.basename(file['path']))
			file['name'] = filename
			urllib.urlretrieve(file['path'], os.path.join(target_dir, filename))
			package_context['files'] += [ filename ]
		for docker_image in package.get('docker_images', []):
			filename = docker_image.lower().replace('/','-').replace(':','-') + '.tgz'
			download_docker_image(docker_image, os.path.join(target_dir, filename), cache=context.get('docker_cache', None))
			package_context['files'] += [ filename ]
	if package.get('is_app', False):
		manifest = package.get('manifest', { 'name': name })
		if manifest.get('random-route', False):
			print >> sys.stderr, 'Illegal manifest option in package', name + ': random-route is not supported'
			sys.exit(1)
		manifest_file = os.path.join(target_dir, 'manifest.yml')
		with open(manifest_file, 'wb') as f:
			f.write('---\n')
			f.write(yaml.safe_dump(manifest, default_flow_style=False))
		package_context['files'] += [ 'manifest.yml' ]
		update_memory(context, manifest)
	template.render(
		os.path.join(package_dir, 'spec'),
		os.path.join(template_dir, 'spec'),
		package_context
	)
	template.render(
		os.path.join(package_dir, 'packaging'),
		os.path.join(template_dir, 'packaging'),
		package_context
	)
开发者ID:pombredanne,项目名称:tile-generator,代码行数:58,代码来源:build.py


示例9: vote_count_get

def vote_count_get():
	user = process_cookie(request.get_cookie("login"))
	if user is None or user.username != "admin":
		return template.render("home_redirect.html",
						{'message': """<h1>You can't view the vote count if you are not admin</h1>"""})
	votes_dict = vote.vote_count()
	votes_list = map(lambda x: (x, votes_dict[x][0], votes_dict[x][1]), votes_dict)
	votes_list.sort(key = lambda x: x[1], reverse=True)

	return template.render("vote_count.html", 
					{'config': config, 'vote_count': votes_list})
开发者ID:DpEpsilon,项目名称:NBHS-Voting-Site,代码行数:11,代码来源:main.py


示例10: get_render

    def get_render(self,template_file,values):
        template_file=template_file+".html"
        self.template_vals.update(values)
        logging.info("-----------------")
        try:
            #sfile=getattr(self.blog.theme, template_file)
            logging.debug("get_render:"+template_file)
            html = micolog_template.render(self.blog.theme, template_file, self.template_vals)
        except TemplateDoesNotExist:
            #sfile=getattr(self.blog.default_theme, template_file)
            html = micolog_template.render(self.blog.default_theme, template_file, self.template_vals)

        return html
开发者ID:linin,项目名称:micolog,代码行数:13,代码来源:base.py


示例11: testRun

 def testRun(self):
     self.assertEqual(render(content="{{for i in range(n):}}{{=i}}{{pass}}", context=dict(n=3)), "012")
     self.assertEqual(render(content="{{if n>2:}}ok{{pass}}", context=dict(n=3)), "ok")
     self.assertEqual(render(content="{{try:}}{{n/0}}{{except:}}fail{{pass}}", context=dict(n=3)), "fail")
     self.assertEqual(render(content='{{="<&>"}}'), "&lt;&amp;&gt;")
     self.assertEqual(render(content='"abc"'), '"abc"')
     self.assertEqual(render(content='"a\'bc"'), '"a\'bc"')
     self.assertEqual(render(content='"a"bc"'), '"a"bc"')
     self.assertEqual(render(content=r'''"a\"bc"'''), r'"a\"bc"')
     self.assertEqual(render(content=r'''"""abc\""""'''), r'"""abc\""""')
开发者ID:zjorundur,项目名称:eve-metrics,代码行数:10,代码来源:test_template.py


示例12: nominate_post

def nominate_post():
	page = Page('/nominate', 'Nominate')
	if page not in pages:
		abort(404)
	current_user = process_cookie(request.get_cookie("login"))
	nominee_fields = config['nominee_fields']
	given_csrf_key = request.forms.get('csrf')
	
	if current_user is None:
		redirect('/login?message=3')

	if not csrf.check_csrf_key(current_user.userid, given_csrf_key):
		abort(403, "A potential CSRF attack was detected. "
			  "Please try again later.")
	
	if current_user.student_info is None:
		return template.render("home_redirect.html",
							   {'message': "<h1>Staff cannot nominate</h1>"})
	
	if not current_user.student_info.is_nominee and config['prenominate']:
		return template.render("home_redirect.html",
							   {'message': "<h1>You are not a candidate.</h1>"})
	
	nominee_fields = filter(
		lambda x: x['name'] not in current_user.student_info.nominee_fields,
		nominee_fields)

	if len(nominee_fields) == 0:
		return template.render("home_redirect.html",
							   {'message': """<h1>You have already
 submitted your nomination</h1>"""})

	truncated = False
	
	for field in nominee_fields:
		submission = request.forms.getunicode(field['name'])
		if len(submission) > field['character_limit']:
			truncated = True
			submission = submission[:650] + "...[truncated]"
		print "sub:", repr(submission)
		submissions.add_nominee_field(current_user.userid,
									  field['name'], submission)

	if not config['prenominate']:
		submissions.add_nominee(current_user.userid)
	
	return template.render("home_redirect.html",
						   {'message': "<h1>Submitted" +
							" (truncated)" if truncated else "" +
							"</h1>"})
开发者ID:DpEpsilon,项目名称:NBHS-Voting-Site,代码行数:50,代码来源:main.py


示例13: get_render

    def get_render(self,template_file,values):
        if self.isPhone():
            template_file=os.path.join('m',template_file+".html")
        else:
            template_file=template_file+".html"
        self.template_vals.update(values)
        logging.info("-----------------")
        try:
            #sfile=getattr(self.blog.theme, template_file)
            logging.debug("get_render:"+template_file)
            html = micolog_template.render(self.blog.theme, template_file, self.template_vals,debug=settings.DEBUG)
        except TemplateDoesNotExist:
            #sfile=getattr(self.blog.default_theme, template_file)
            html = micolog_template.render(self.blog.default_theme, template_file, self.template_vals,debug=settings.DEBUG)

        return html
开发者ID:gkso,项目名称:micolog,代码行数:16,代码来源:base.py


示例14: get

    def get(self, *path):
        root = cherrypy.request.app.config['video']['path']
        fullpath = os.path.join(root, *path)

        f = Item.create(root, path, path[-1])
        url = urllib.quote(os.path.join(*path).encode('utf-8'))

        refs = []
        for x in cherrypy.request.app.config['refs']:
            ref = x
            href = '#'
            try:
                href = cherrypy.request.app.config['refs'][x].format(id=f[x])
            except KeyError:
                pass
            refs.append((x, href))

        # meta data which is always visible
        meta = {
            'Genre': None,
            'Tags': None,
            'Year': None
        }

        return template.render(url=url, file=f, refs=refs, meta=meta)
开发者ID:ext,项目名称:videogui,代码行数:25,代码来源:browser.py


示例15: get

    def get(self):
        files = template.variable()
        tagQuery = self.request.get('tag')

        if (tagQuery):
            for f in File.all().ancestor(FILE_LIST).filter("tag =", tagQuery).order('-uploaded_at'):
                fileString =  '<li><a href="/download/%s">%s</a> Tags:' \
                                % (f.name, f.name)
                for t in f.tag:
                    fileString += '<a href="/list?tag=%s">%s</a>, ' \
                            % (t, t)
                print >>files, fileString
        else:               
            for f in File.all().ancestor(FILE_LIST).order('-uploaded_at'):
                fileString =  '<li><a href="/download/%s">%s</a> Tags:' \
                                % (f.name, f.name)
                for t in f.tag:
                    fileString += '<a href="/list?tag=%s">%s</a>, ' \
                                % (t, t)
                print >>files, fileString
                
        html = template.render(
            'list.html',
            {'file_list': files},
            escaped=False
        )
        self.response.write(html)
开发者ID:stengerben,项目名称:CPSC473Repo,代码行数:27,代码来源:main.py


示例16: generate_sitemap

 def generate_sitemap(self, filename='sitemap.xml'):
     map_path = os.path.join(self.config.site_dir, filename)
     log.info('Generating sitemap at %s' % map_path)
     sitemap = template.render(
         SITE_MAP, 
         {'posts' : self.posts, 'pages' : self.pages})
     self.write_html(map_path, sitemap)
开发者ID:anoopjoe,项目名称:voldemort,代码行数:7,代码来源:__init__.py


示例17: responseClub

	def responseClub(self, clubmodel, nickname):
		templateValues = dict(action=self.request.path, username=nickname, model=clubmodel)
		if (hasClubPrivilige(users.get_current_user(), clubmodel, "finance" )):
			templateValues['enableFinance'] = True
		if (clubmodel.is_saved()):
			templateValues['oldslug'] = clubmodel.slug
		self.response.out.write (render(self.template, templateValues, self.request.url) )
开发者ID:cardmaster,项目名称:makeclub,代码行数:7,代码来源:clubedit.py


示例18: paginate

    def paginate(self, filename, page_meta):
        """Paginate the content in the file
        """
        log.info('Paginating page %s' % filename)
        for pgr in self.paginator:
            log.debug('Paginating: %s' % pgr)
            html = template.render(
                page_meta['raw'], 
                {'page': page_meta, 'paginator': pgr})
            if pgr.current_page == 1:
                paginator_path = os.path.join(self.config.site_dir,
                    filename.split(self.work_dir)[1][1:])
                log.debug('Generating page %s' % paginator_path)
                self.write_html(paginator_path, html)

            current_page = 'page%s' %pgr.current_page
            site_path, ext = os.path.splitext(
                filename.split(self.work_dir)[1][1:])
            if site_path == 'index': site_path = '';
            paginator_path = os.path.join(
                self.config.site_dir,
                site_path,
                current_page,
                'index.html')

            log.debug('Generating page %s' % paginator_path)
            # write the rendered page
            self.write_html(paginator_path, html)
开发者ID:anoopjoe,项目名称:voldemort,代码行数:28,代码来源:__init__.py


示例19: send_diff_by_email

def send_diff_by_email(cfg, module, revision, log, diff):
    logger = logging.getLogger(module)

    subscribers = cfg.get(MAIN_CONFIG_SECTION, OPT_SUBSCRIBERS)
    if cfg.has_option(module, OPT_SUBSCRIBERS):
        subscribers = cfg.get(module, OPT_SUBSCRIBERS)

    # create message
    context = {
        "revision": revision,
        "author": log.author_name,
        "timestamp": log.timestamp,
        "message": escape_html(log.message),
        "diff": escape_html(diff),
        "files": diffparser.get_files(diff, cfg.get(module, OPT_REPO))
    }
    
    msg_str = template.render(open(TEMPLATE_FILE, 'r').read(), context)
    
    # create email message
    from_domain = cfg.get(MAIN_CONFIG_SECTION, OPT_FROM_DOMAIN)
    from_addr = "%[email protected]%s" % (log.author, from_domain)
    msg = MIMEText(msg_str, "html")
    msg['Subject'] = "[svn-diff for %s, r%d] %s" % (module, revision, log.message)
    msg['From'] = from_addr 
    msg['To'] = subscribers
    
    # connect to SMTP server and send message
    smtp_server = cfg.get(MAIN_CONFIG_SECTION, OPT_SMTPSERVER)
    logger.info("Sending mail to %s through %s from %s" , subscribers, smtp_server, from_addr)
    s = smtplib.SMTP(smtp_server)
    #s.connect()
    s.sendmail(from_addr, subscribers.split(','), msg.as_string(False))
    s.close()
开发者ID:kostya-sh,项目名称:svn-diff,代码行数:34,代码来源:svndiff.py


示例20: get

    def get(self):
        files = File.all().ancestor(FILE_LIST).order('-uploaded_at')

        tag = self.request.GET.get('tag')
        if tag:
            files = files.filter('tags =', tag)

        file_list = template.variable()
        for f in files:
            print >>file_list, '<tr>'
            print >>file_list, '<td><a href="/download/%s">%s</a></td>' \
                            % (f.name, f.name)
            print >>file_list, '<td>'
            for tag in f.tags:
                print >>file_list, '<a href="/list?tag=%s">%s</a>' \
                                % (tag, tag)
            print >>file_list, '</td>'
            print >>file_list, '</tr>'

        html = template.render(
            'list.html',
            {'file_list': file_list},
            escaped=False
        )
        self.response.write(html)
开发者ID:CKnotts,项目名称:cpsc473,代码行数:25,代码来源:main.py



注:本文中的template.render函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python template.template函数代码示例发布时间:2022-05-27
下一篇:
Python template.parse_template函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap