当前位置: 首页>>代码示例>>Python>>正文


Python Template.Template类代码示例

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


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

示例1: search

 def search( self, searchQuery="", where="" ):
     symbols = {}
     symbols["searchQuery"] = searchQuery
     symbols["where"]       = where
     symbols["title"]       = ""
     template = Template( file=os.path.join( const.DATA_ROOT, "assets/webui/search.html.tmpl" ), searchList=symbols )
     return template.respond()
开发者ID:jansaris,项目名称:AminoPVR,代码行数:7,代码来源:webui.py

示例2: four

    def four(self, **kwargs):
        """ Accept Indexers and show Restart screen """
        if kwargs:
            if 'newzbin_user' in kwargs and 'newzbin_pass' in kwargs:
                cfg.newzbin_username.set(kwargs.get('newzbin_user',''))
                cfg.newzbin_password.set(kwargs.get('newzbin_pass',''))
            cfg.newzbin_bookmarks.set(kwargs.get('newzbin_bookmarks', '0'))
            if 'matrix_user' in kwargs and 'matrix_apikey' in kwargs:
                cfg.matrix_username.set(kwargs.get('matrix_user',''))
                cfg.matrix_apikey.set(kwargs.get('matrix_apikey',''))

        config.save_config()

        # Show Restart screen
        info = self.info.copy()
        info['num'] = '» %s' % T('Step Four')
        info['number'] = 4
        info['helpuri'] = 'http://wiki.sabnzbd.org/'
        info['session'] = cfg.api_key()

        info['access_url'], info['urls'] = self.get_access_info()
        info['T'] = Ttemplate

        template = Template(file=os.path.join(self.__web_dir, 'four.html'),
                            searchList=[info], compilerSettings=sabnzbd.interface.DIRECTIVES)
        return template.respond()
开发者ID:Adrellias,项目名称:sabnzbd,代码行数:26,代码来源:wizard.py

示例3: usertasks

 def usertasks(self,task_name=None,pageNumber=1,nPerPage=1500,callback=None,**kwargs):
     ''' usertasks returns celery tasks perform and the link to the task result page.
         task_name-  string optional
         pageNumber and nPerPage is optional
     ''' 
     db=self.db[self.database][self.collection]
     try:
         page=int(pageNumber)
         perPage=int(nPerPage)
     except:
         page=1
         perPage=100
     try:
         if cherrypy.request.login:
             user = cherrypy.request.login
         else:
             user = "guest"
     except:
         pass 
     if not task_name:
         res=db.find({'user':user}).skip((page-1)* int(nPerPage)).limit(int(nPerPage)).sort([('timestamp',-1)]) 
         rows=db.find({'user':user}).count()
     else:
         res=db.find({'user':user,'task_name':task_name}).skip((page-1) * int(nPerPage)).limit(int(nPerPage)).sort([('timestamp',-1)])
         rows=db.find({'user':user,'task_name':task_name}).count()
     ePage= int(math.ceil(float(rows)/float(perPage)))
     nameSpace = dict(tasks=res,page=page,endPage=ePage)#tresult)
     #t = Template(file = templatepath + '/usertasks.tmpl', searchList=[nameSpace])
     if callback:
         t = Template(file = templatepath + '/usertasks_call.tmpl', searchList=[nameSpace])
         return str(callback) + "(" + json.dumps({'html':t.respond()}) + ")"
     else:
         t = Template(file = templatepath + '/usertasks.tmpl', searchList=[nameSpace])
         return t.respond()
开发者ID:jduckles,项目名称:queue,代码行数:34,代码来源:queue_status.py

示例4: get

    def get(self, resource):
        resid = resource 
	l_skel = Skel()
	l_skel.title = "Smashed.in :: OverHeards"

        meme_query = UserMemeDb.query(UserMemeDb.resid == resid)
        memes = meme_query.fetch(1)
        meme = memes[0]
        template_values = {
            'memeurl':   '/res/download/%s' % meme.blobid,
            'conturl':   '/oh/%s' % meme.resid,
            'localid':   '%s' % meme.resid,
            'mode'   :   '%s' %meme.mode,
            'shareid':   '%s' % meme.shareid,
            'currentid': '%s' % meme.resid,
            'commentid': '%s' % meme.commentid,
            'isLoggedIn': '%s' %self.logged_in,
            'tags'      : ','.join(meme.tags)
            
            }

	#Head
	head_path = os.path.join (os.path.dirname(__file__), 'templates/ohview-head.tmpl')
	l_skel.addtohead(str((Template.compile(file=head_path)(searchList=template_values))))

	#body
        path = os.path.join (os.path.dirname (__file__), 'templates/ohview-body.tmpl')
	l_skel.addtobody (str((Template.compile(file=path)(searchList=template_values))))

        self.response.out.write(l_skel.gethtml())
开发者ID:thejasvibhat,项目名称:smashed,代码行数:30,代码来源:meme.py

示例5: two

    def two(self, **kwargs):
        """ Accept server and show internal web server page """
        # Save server details
        if kwargs:
            kwargs['enable'] = 1
            sabnzbd.interface.handle_server(kwargs)

        # Create web server page
        info = self.info.copy()
        info['num'] = '» %s' % T('Step Two')
        info['number'] = 2
        info['T'] = Ttemplate

        host = cfg.cherryhost()
        info['host'] = host
        # Allow special operation if host is not one of the defaults
        if host not in ('localhost','0.0.0.0'):
            info['custom_host'] = True
        else:
            info['custom_host'] = False

        info['have_ssl'] = bool(sabnzbd.newswrapper.HAVE_SSL)
        info['enable_https'] = cfg.enable_https()
        info['autobrowser'] = cfg.autobrowser()
        info['web_user'] = cfg.username()
        info['web_pass'] = cfg.password()

        template = Template(file=os.path.join(self.__web_dir, 'two.html'),
                            searchList=[info], compilerSettings=sabnzbd.interface.DIRECTIVES)
        return template.respond()
开发者ID:Adrellias,项目名称:sabnzbd,代码行数:30,代码来源:wizard.py

示例6: output_result

 def output_result(self, methodname, template, result, action_metadata, outf,
                   return_template=False):
     """
     Renders a response body
     """
     from Cheetah.Template import Template
     # any result with custom serialization
     if action_metadata.get('return_type') == 'plain':
         outf.write(str(result))
     elif callable(result):
         outf.write(result())
     # JSON with simple serialization (dict -> string)
     elif action_metadata.get('return_type') == 'json':
         json.dump(result, outf)
     # Template
     elif type(result) is DictType:
         self.add_globals(result, methodname, action_metadata)
         if template.endswith('.tmpl'):
             template_class = self._get_template_class(template[:-5])
             tpl_ans = template_class(searchList=[result, self.args])
         else:
             tpl_ans = Template(template, searchList=[result, self.args])
         if return_template:
             return tpl_ans
         tpl_ans.respond(CheetahResponseFile(outf))
开发者ID:tomachalek,项目名称:kontext,代码行数:25,代码来源:__init__.py

示例7: test_normalizePreprocessorArgVariants

    def test_normalizePreprocessorArgVariants(self):
        src='%set foo = 12\n%%comment\n$(@foo*10)'

        class Settings1: tokens = '@ %' 
        Settings1 = Settings1()
            
        from Cheetah.Template import TemplatePreprocessor
        settings = Template._normalizePreprocessorSettings(Settings1)
        preprocObj = TemplatePreprocessor(settings)

        def preprocFunc(source, file):
            return '$(12*10)', None

        class TemplateSubclass(Template):
            pass

        compilerSettings = {'cheetahVarStartToken':'@',
                            'directiveStartToken':'%',
                            'commentStartToken':'%%',
                            }
        
        for arg in ['@ %',
                    {'tokens':'@ %'},
                    {'compilerSettings':compilerSettings},
                    {'compilerSettings':compilerSettings,
                     'templateInitArgs':{}},
                    {'tokens':'@ %',
                     'templateAPIClass':TemplateSubclass},
                    Settings1,
                    preprocObj,
                    preprocFunc,                    
                    ]:
            
            klass = Template.compile(src, preprocessors=arg)
            assert str(klass())=='120'
开发者ID:andrenalin1981,项目名称:qpkg-sickbeard,代码行数:35,代码来源:Template.py

示例8: get_data

 def get_data(self, entry, metadata):
     template = Template(self.data.decode(self.encoding),
                         compilerSettings=self.settings)
     template.metadata = metadata
     template.path = entry.get('realname', entry.get('name'))
     template.source_path = self.name
     return template.respond()
开发者ID:ab,项目名称:bcfg2,代码行数:7,代码来源:CfgCheetahGenerator.py

示例9: render_template

def render_template(plugin, vm, tmplname, context=None):
    # Import here to avoid having to build-dep on python-cheetah
    from   Cheetah.Template import Template
    searchList = []
    if context:
        searchList.append(context)
    searchList.append(vm)

    tmpldirs = [os.path.expanduser('~/.vmbuilder/%s'),
                os.path.dirname(__file__) + '/plugins/%s/templates',
                '/etc/vmbuilder/%s']

    if vm.templates:
        tmpldirs.insert(0,'%s/%%s' % vm.templates)
    
    tmpldirs = [dir % plugin for dir in tmpldirs]

    for dir in tmpldirs:
        tmplfile = '%s/%s.tmpl' % (dir, tmplname)
        if os.path.exists(tmplfile):
            t = Template(file=tmplfile, searchList=searchList)
            output = t.respond()
            logging.debug('Output from template \'%s\': %s' % (tmplfile, output))
            return output

    raise VMBuilderException('Template %s.tmpl not found in any of %s' % (tmplname, ', '.join(tmpldirs)))
开发者ID:SafPlusPlus,项目名称:vmbuilder,代码行数:26,代码来源:util.py

示例10: get_config_from_template

    def get_config_from_template(self, tmpl_path, vars_dict):
        logging.debug("template path is %s", tmpl_path)
        logging.debug("vars_dict is %s", vars_dict)

        if not os.path.exists(tmpl_path) or not vars_dict:
            logging.info("Template dir or vars_dict is None!")
            return {}

        searchList = []
        copy_vars_dict = deepcopy(vars_dict)
        for key, value in vars_dict.iteritems():
            if isinstance(value, dict):
                temp = copy_vars_dict[key]
                del copy_vars_dict[key]
                searchList.append(temp)
        searchList.append(copy_vars_dict)

        # Load base template first if it exists
        base_config = {}
        base_tmpl_path = os.path.join(os.path.dirname(tmpl_path), 'base.tmpl')
        if os.path.isfile(base_tmpl_path) and base_tmpl_path != tmpl_path:
            base_tmpl = Template(file=base_tmpl_path, searchList=searchList)
            base_config = json.loads(base_tmpl.respond(), encoding='utf-8')
            base_config = json.loads(json.dumps(base_config), encoding='utf-8')

        # Load specific template for current adapter
        tmpl = Template(file=open(tmpl_path, "r"), searchList=searchList)
        config = json.loads(tmpl.respond(), encoding='utf-8')
        config = json.loads(json.dumps(config), encoding='utf-8')

        # Merge the two outputs
        config = util.merge_dict(base_config, config)

        logging.debug("get_config_from_template resulting %s", config)
        return config
开发者ID:huawei-gts,项目名称:compass-core,代码行数:35,代码来源:installer.py

示例11: do_replay_from_yaml

def do_replay_from_yaml (args):
    print "Replaying using %s" % args.yamlfile

    replay_file_name = "%s_replay.sh" % args.project
    replay_file = open (replay_file_name, "w")
    bpy = skel_bpy.skel_bpy (args.yamlfile)

    # Generate replay_yaml.sh shell script
    from Cheetah.Template import Template
    template_file = open (os.path.expanduser("~/.skel/templates/replay_yaml.tmpl"), 'r')
    t = Template(file=template_file)
    t.bpy = bpy

    # No, I don't like these either.
    t.yamlfile = args.yamlfile
    t.project = args.project
    t.force = args.force

    replay_file.write (str(t) )

    replay_file.close()

    # Adjust the permissions of the replay script to make it runnable by user
    os.chmod (replay_file_name, stat.S_IXUSR | stat.S_IWUSR | stat.S_IRUSR)

    # Run it
    subprocess.check_call ("./%s" % replay_file_name)
开发者ID:icedwater,项目名称:ADIOS,代码行数:27,代码来源:skel_replay.py

示例12: infopage

    def infopage(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        t = Template(file=os.path.join(SCRIPTDIR, 'templates',
                                       'info_page.tmpl'))
        t.admin = ''
        for section, settings in config.getShares():
            if 'type' in settings and settings['type'] == 'admin':
                t.admin += '<a href="/TiVoConnect?Command=Admin&Container=' + section\
                           + '">pyTivo Web Configuration</a><br>'\
                           + '<a href="/TiVoConnect?Command=NPL&Container=' + section\
                           + '">pyTivo ToGo</a><br>'
        if t.admin == '':
            t.admin = '<br><b>No Admin plugin installed in pyTivo.conf</b><br> If you wish to use'\
                      + ' the admin plugin add the following lines to pyTivo.conf<br><br>'\
                      + '[Admin]<br>type=admin'

        t.shares = 'Video shares:<br/>'
        for section, settings in config.getShares():
            if settings.get('type') == 'video':
                t.shares += '<a href="TiVoConnect?Command=QueryContainer&Container=' + section\
                    + '">' +  section + '</a><br/>'
        
        self.wfile.write(t)
        self.end_headers()
开发者ID:armooo,项目名称:pytivo,代码行数:26,代码来源:httpserver.py

示例13: gen_suite_with_args

def gen_suite_with_args (parent_parser):
    args = pparse_command_line (parent_parser)

    print "Generating test suite using %s" % args.yamlfile

    suite_gen_file_name = "%s_gen_suite.sh" % args.project
    suite_gen_file = open (suite_gen_file_name, "w")
    plan = skel_test_plan.skel_test_plan (args.yamlfile)

    # Generate gen_suite.sh shell script
    from Cheetah.Template import Template
    template_file = open (os.path.expanduser("~/.skel/templates/create_suite.tmpl"), 'r')
    t = Template(file=template_file)
    t.test_plan = plan

    # No, I don't like these either.
    t.yamlfile = args.yamlfile
    t.project = args.project
    t.force = args.force

    suite_gen_file.write (str(t) )

    suite_gen_file.close()

    # Adjust the permissions of the replay script to make it runnable by user
    os.chmod (suite_gen_file_name, stat.S_IXUSR | stat.S_IWUSR | stat.S_IRUSR)

    # Run it
    #print "Run ./%s [disabled]" % suite_gen_file_name
    subprocess.check_call ("./%s" % suite_gen_file_name)
开发者ID:Dumbear,项目名称:ADIOS,代码行数:30,代码来源:skel_suite.py

示例14: application

def application(environ, start_response):

	connector = MySQLdb.connect(host="192.168.30.10",
                                    db="personal",
                                    user="vagrant",
                                    passwd="vagrant",
                                    charset="utf8")
	cursor = connector.cursor()
	cursor.execute("SELECT * FROM info")
	result = cursor.fetchall()

	start_response('200 OK', [('Content-Type', 'text/html')])

	tpl = Template(file="/var/www/wsgi/test/tpl/result.tpl")
	tpl.data = []

	for row in result:
		if str(row[3]) == "M":
			tpl.data.append((str(row[0]), str(row[2]), "Man", str(row[4]), str(row[5])))
		else:
			tpl.data.append((str(row[0]), str(row[2]), "Woman", str(row[4]), str(row[5])))
			
	cursor.close()
	connector.close()

	return tpl.respond().encode('utf-8')
开发者ID:kakky0312,项目名称:test-scripts,代码行数:26,代码来源:load_db.py

示例15: test_int

 def test_int(self):
     from Cheetah.Template import Template
     t = Template('''
         #def intify(val)
             #return $int(val)
         #end def''', compilerSettings={'useStackFrames' : False})
     self.assertEquals(5, t.intify('5'))
开发者ID:tiarno,项目名称:cheetah,代码行数:7,代码来源:NameMapper.py


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