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

Python template.Template类代码示例

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

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



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

示例1: writeVhost

def writeVhost(settings, domain, templateName, values):
	"""Writes a site's vhost configuration file"""
	
	# Open the file
	conf = str(os.path.join(settings['confdir'], domain))
	outFile = open(conf, 'w')
	
	
	# Write the configuration
	t = Template()
	try:
		tplDir = os.path.join(settings['templates'], templateName)
		templateFilename = os.path.join(tplDir, templateName + '.tpl')
		inFile  = open(templateFilename, 'r')
		source = inFile.read()
		
		# While there are variables left unprocessed, process the string
		expression = r'\[\%.+\%\]'
		while re.search(expression, source) != None:
			source = t.processString(source, values)
		
		# Write what we have
		outFile.write(source)
	except TemplateException, e:
		print "ERROR: %s" % e
开发者ID:rnelson,项目名称:mksite,代码行数:25,代码来源:mksite.py


示例2: testCompile

  def testCompile(self):
    ttcfg = { "POST_CHOMP": 1,
              "INCLUDE_PATH": "test/src",
              "COMPILE_EXT": ".ttc" }
    # Check that compiled template files exist.
    compiled = "test/src/foo.ttc"
    self.assert_(os.path.exists(compiled))
    self.assert_(os.path.exists("test/src/complex.ttc"))

    # Ensure template metadata is saved in compiled file.
    output = Template(ttcfg).process("baz", { "showname": 1 })
    self.assertNotEqual(-1, output.find("name: baz"))

    # We're going to hack on the foo.ttc file to change some key text.
    # This way we can tell that the template was loaded from the compiled
    # version and not the source.
    fh = open(compiled, "r+")
    stat = os.fstat(fh.fileno())
    foo = fh.read()
    fh.seek(0)
    fh.write(foo.replace("the foo file", "the hacked foo file"))
    fh.close()
    os.utime(compiled, (stat.st_atime, stat.st_mtime))

    self.Expect(DATA, ttcfg)
开发者ID:vaMuchenje,项目名称:Template-Python,代码行数:25,代码来源:compile2_test.py


示例3: testContext

  def testContext(self):
    tt = Template({ 'INCLUDE_PATH': 'test/src:test/lib',
                    'TRIM': True,
                    'POST_CHOMP': 1 })
    ttpython = Template({ 'INCLUDE_PATH': 'test/src:test/lib',
                          'TRIM': True,
                          'POST_CHOMP': 1,
                          'EVAL_PYTHON': True })

    ctx = tt.service().context()
    self.failUnless(ctx)
    self.assertEquals(ctx, tt.context())
    self.failUnless(ctx.trim())
    self.failUnless(not ctx.eval_python())
    ctx = ttpython.service().context()
    self.failUnless(ctx)
    self.failUnless(ctx.trim())
    self.failUnless(ctx.eval_python())

    # template()

    # Test that we can fetch a template via template()
    tmpl = ctx.template('header')
    self.failUnless(tmpl)
    self.failUnless(isinstance(tmpl, Document))

    # Test that non-existence of a template is reported
    error = None
    try:
      tmpl = ctx.template('no_such_template')
    except Exception, e:
      error = e
开发者ID:vaMuchenje,项目名称:Template-Python,代码行数:32,代码来源:context_test.py


示例4: testInclude

  def testInclude(self):
    callsign = self._callsign()
    replace = { "a": callsign["a"],
                "b": callsign["b"],
                "c": { "d": callsign["d"],
                       "e": callsign["e"],
                       "f": { "g": callsign["g"],
                              "h": callsign["h"] } },
                "r": callsign["r"],
                "s": callsign["s"],
                "t": callsign["t"] }
    tproc = Template({ "INTERPOLATE": True,
                       "INCLUDE_PATH": "test/src:test/lib",
                       "TRIM": True,
                       "AUTO_RESET": False,
                       "DEFAULT": "default" })
    incpath = [ "test/src", "/nowhere" ]
    tt_reset = Template({ "INTERPOLATE": True,
                          "INCLUDE_PATH": incpath,
                          "TRIM": True,
                          "RECURSION": True,
                          "DEFAULT": "bad_default" })
    incpath[1] = "test/lib"

    replace["metaout"] = tproc.process("metadata", replace)
    replace["metamod"] = os.stat("test/src/metadata").st_mtime

    self.Expect(DATA, (('default', tproc), ('reset', tt_reset)), replace)
开发者ID:vaMuchenje,项目名称:Template-Python,代码行数:28,代码来源:include_test.py


示例5: create_user

def create_user(ldap_server, user):
    old_user = find_user(ldap_server, config, user['USER_NAME'])

    if old_user is None:
        user['USER_ID'] = str(get_free_user_id(ldap_server))
        user['USER_UID'] = str(uuid.uuid4())
    else:
        user['USER_ID'] = old_user['uidNumber'][0]
        user['USER_UID'] = old_user['apple-generateduid'][0]

    group = find_group(l, config, user['USER_GROUP_NAME'])
    user['USER_GROUP_ID'] = group['gidNumber'][0]

    user['USER_PASSWORD_HASH'] = "{KERBEROS} " + user['USER_NAME']

    t = Template("../../config/plab-ldap/templates/user.ldif")
    t.replace(config)
    t.replace(user)
    insert_ldif(ldap_server, str(t))

    add_to_group(ldap_server, config, user['USER_NAME'], user['USER_GROUP_NAME'])

    # Get user and show details
    group = find_group(ldap_server, config, user['USER_GROUP_NAME'])
    user = find_user(ldap_server, config, user['USER_NAME'])

    pp = pprint.PrettyPrinter(indent = 4)

    print "Added user (" + user['uid'][0] + ") with id (" + str(user['uidNumber']) + ")"
开发者ID:PolaviejaLab,项目名称:psychophysics,代码行数:29,代码来源:step_5_create_users.py


示例6: make_admin_staff_panel

    def make_admin_staff_panel(self):
        session = model.Session()
        table = model.account
        sql = table.select().order_by(table.c.account.asc(), table.c.username.asc())

        query = session.execute(sql)
        users = [dict(row.items()) for row in query]

        rowtype = 1
        for row in users:
            # Alternate between values 1 and 2.
            rowtype ^= 0x3
            row["rowtype"] = rowtype

            # Get latest action from DB.
            action_table = model.activity
            action_grab_sql = (
                action_table.select()
                .where(action_table.c.username == row["username"])
                .order_by(action_table.c.date.desc())
            )
            last_action = session.execute(action_grab_sql).fetchone()

            # Copy to row.
            if last_action:
                row["action"] = last_action["action"]
                row["actiondate"] = last_action["date"]
            else:
                row["action"] = None
                row["actiondate"] = None

        Template.__init__(self, "staff_management", users=users)
开发者ID:dequis,项目名称:wakarimasen,代码行数:32,代码来源:staff_interface.py


示例7: generate

            def generate(self):
                print("=== Generating mocks for %s" % self.header_file)
                cwd_stored = os.getcwd()
                scriptdir = os.path.dirname(os.path.realpath(__file__))

                print("Parsing file...")
                os.chdir(self.tempdir)
                fdv = FuncDeclVisitor(self.args)
                fdv.parse(os.path.realpath(self.header_prep))

                if self.args.print_ast:
                    # pprint(v.funcdecls)
                    fdv.ast.show(attrnames=True, nodenames=True)

                if fdv.funcdecls:
                    HFile = collections.namedtuple(
                        'File', ['name', 'incl', 'funcs'])
                    file = HFile(name=self.header_name,
                                 incl=self.header_file,
                                 funcs=fdv.funcdecls)
                    os.chdir(scriptdir + "/../tmpl")
                    print("Generating %s" % (self.filemock_h))
                    self.mockh = Template("file.h.tmpl")
                    self.mockh.render({'file': file})
                    print("Generating %s" % (self.filemock_c))
                    self.mockc = Template("file.c.tmpl")
                    self.mockc.render({'file': file})
                else:
                    print("No function declarations found in %s" % (self.header_file))

                # restore cwd
                os.chdir(cwd_stored)
开发者ID:alveko,项目名称:easymock,代码行数:32,代码来源:easymockgen.py


示例8: generate

	def generate(self, section=None):
		if section is None:
			section = self.navigation.root
		t = Template(self, section)
		t.generate()

		for child in section.childs:
			self.generate(child)
开发者ID:christoph-frick,项目名称:ofnircms,代码行数:8,代码来源:ofnircms.py


示例9: _generate

 def _generate(self, path=None, output=None):
     if not output:
         output = self.args.output
     if not path:
         path = self.args.template
     template = Template(path=path, output=output,
                         seed=self.args.seed, quiet=self.args.quiet)
     template.generate()
开发者ID:bukka,项目名称:jsogen,代码行数:8,代码来源:jsogen.py


示例10: testError

 def testError(self):
   tmpl = Template({ 'BLOCKS': { 'badinc': '[% INCLUDE nosuchfile %]' } })
   try:
     tmpl.process("badinc")
     self.fail("Failed to raise exception")
   except TemplateException, e:
     self.assertEquals('file', e.type())
     self.assertEquals('nosuchfile: not found', e.info())
开发者ID:vaMuchenje,项目名称:Template-Python,代码行数:8,代码来源:error_test.py


示例11: make_admin_post_search_panel

    def make_admin_post_search_panel(self, search, text, caller='internal'):
        board = self.board
        session = model.Session()
        table = board.table

        board.check_access(self.user)

        popup = caller != 'board'

        if search.find('IP Address') != -1:
            try:
                sql = table.select()\
                           .where(table.c.ip == misc.dot_to_dec(text))
            except ValueError:
                raise WakaError('Please enter a valid IP.')
            search_type = 'IP'
        elif search.find('Text String') != -1:
            sql = table.select().where(table.c.comment.like('%'+text+'%'))
            search_type = 'text string'
        elif search.find('Author') != -1:
            sql = table.select().where(or_(table.c.name.like('%'+text+'%'),
                table.c.trip.like('%'+text+'%')))
            search_type = 'author'
        else:
            sql = table.select().where(table.c.num == text)
            search_type = 'ID'

        if search_type != 'ID':
            page = model.Page(sql, self.page, self.perpage)
            rowcount = page.total_entries
            total_pages = page.total_pages
            posts = page.rows
            if not posts:
                raise WakaError("No posts found for %s %s" % (search_type, text))
        else:
            rowcount = total_pages = 1
            row = session.execute(sql).fetchone()
            if not row:
                raise WakaError("Post not found. (It may have just been"
                                " deleted.)")
            posts = [row]


        inputs = [
            {'name': 'board', 'value': board.name},
            {'name' : 'task', 'value' : 'searchposts'},
            {'name' : 'text', 'value' : text},
            {'name': 'caller', 'value': caller},
            {'name' : 'search', 'value': search}
        ]

        rooturl = misc.make_script_url(task='searchposts', board=board.name,
            caller=caller, search=search, text=text, _amp=True)

        Template.__init__(self, 'post_search', num=id,
                          posts=posts, search=search, text=text,
                          inputs=inputs, number_of_pages=total_pages,
                          rooturl=rooturl, rowcount=rowcount, popup=popup)
开发者ID:mouhtasi,项目名称:wakarimasen,代码行数:58,代码来源:staff_interface.py


示例12: make_edit_staff_window

    def make_edit_staff_window(self, username):
        boards = interboard.get_all_boards()
        edited_user = staff.StaffMember.get(username)

        for board in boards:
            if board in edited_user.reign:
                board["underpower"] = True

        Template.__init__(self, "staff_edit_template", user_to_edit=username, boards=boards)
开发者ID:dequis,项目名称:wakarimasen,代码行数:9,代码来源:staff_interface.py


示例13: Expect

  def Expect(self, data, tproc=None, vars=None):
    vars = vars or {}
    data = re.sub(r"(?m)^#.*\n", "", data)
    match = re.search(r"\s*--\s*start\s*--\s*", data)
    if match:
      data = data[match.end():]
    match = re.search(r"\s*--\s*stop\s*--\s*", data)
    if match:
      data = data[:match.start()]
    tests = re.split(r"(?mi)^\s*--\s*test\s*--\s*", data)
    if not tests[0]:
      tests.pop(0)
    ttprocs = None
    if isinstance(tproc, dict):
      tproc = Template(tproc)
    elif isinstance(tproc, (tuple, list)):
      ttprocs = dict(tproc)
      tproc = tproc[0][1]
    elif not isinstance(tproc, Template):
      tproc = Template()
    for count, test in enumerate(tests):
      match = re.search(r"(?mi)^\s*-- name:? (.*?) --\s*\n", test)
      if match:
        name = match.group(1)
        test = test[:match.start()] + test[match.end():]
      else:
        name = "template text %d" % (count + 1)
      match = re.search(r"(?mi)^\s*--\s*expect\s*--\s*\n", test)
      if match:
        input, expect = test[:match.start()], test[match.end():]
      else:
        input, expect = test, ""
      match = re.match(r"(?mi)^\s*--\s*use\s+(\S+)\s*--\s*\n", input)
      if match:
        ttname = match.group(1)
        ttlookup = ttprocs.get(ttname)
        if ttlookup:
          tproc = ttlookup
        else:
          self.fail("no such template object to use: %s\n" % ttname)
        input = input[:match.start()] + input[match.end():]

      try:
        out = tproc.processString(input, vars)
      except Exception, e:
        self.fail("Test #%d: %s process FAILED: %s\n%s" % (
          count + 1, name, subtext(input), e))

      match = re.match(r"(?i)\s*--+\s*process\s*--+\s*\n", expect)
      if match:
        expect = expect[match.end():]
        try:
          expect = tproc.processString(expect, vars)
        except TemplateException, e:
          self.fail("Test #%d: Template process failed (expect): %s" % (
            count + 1, e))
开发者ID:brianfreud,项目名称:MusicBrainz-NGS-Server,代码行数:56,代码来源:test.py


示例14: count_templates

    def count_templates(self):
        """
        Retrieve count of existing templates created by owner of API-key

        API call used is v1/template (GET)

        @return: Integer
        """
        temp_template = Template(api_client=self.api_client)
        return temp_template.count()
开发者ID:tello,项目名称:humble-pie,代码行数:10,代码来源:service.py


示例15: testView

 def testView(self):
     vars = {"foo": Foo(pi=3.14, e=2.718), "blessed_list": MyList("Hello", "World")}
     t = Template()
     context = t.context()
     view = context.view()
     self.assert_(view)
     view = context.view({"prefix": "my"})
     self.assert_(view)
     self.assertEquals("my", view.prefix())
     self.Expect(DATA, None, vars)
开发者ID:vaMuchenje,项目名称:Template-Python,代码行数:10,代码来源:view_test.py


示例16: __init__

    def __init__(self, cookie, board=None, dest=None, page=None, perpage=50, **kwargs):
        try:
            self.user = staff.StaffMember.get_from_cookie(cookie)
        except staff.LoginError:
            Template.__init__(self, "admin_login_template", login_task=dest)
            return
        if not dest:
            dest = HOME_PANEL

        self.admin = cookie

        # TODO: Check if mod is banned.
        if not page:
            if dest in (HOME_PANEL, TRASH_PANEL):
                # Adjust for different pagination scheme. (Blame Wakaba.)
                page = 0
            else:
                page = 1
        if not str(perpage).isdigit():
            perpage = 50

        # The page attribute is not always a pure integer (thread pages).
        if str(page).isdigit():
            page = int(page)
        self.page = page
        self.perpage = int(perpage)
        self.board = local.environ["waka.board"]

        if dest not in INTERFACE_MAPPING:
            dest = HOME_PANEL

        INTERFACE_MAPPING[dest](self, **kwargs)

        # Convert user reign list into a list of dictionaries, for
        # templating.
        reign = []
        if self.user.account == staff.MODERATOR:
            reign = [{"board_entry": entry} for entry in self.user.reign]
        else:
            if self.board:
                reign = interboard.get_all_boards(check_board_name=self.board.name)
            else:
                reign = interboard.get_all_boards()

        # Set global form variables.
        Template.update_parameters(
            self,
            username=self.user.username,
            type=self.user.account,
            admin=cookie,
            boards_select=reign,
            boards=reign,
            page=self.page,
            perpage=self.perpage,
        )
开发者ID:dequis,项目名称:wakarimasen,代码行数:55,代码来源:staff_interface.py


示例17: make_admin_spam_panel

    def make_admin_spam_panel(self):
        # TODO: Paginate this, too.
        spam_list = []
        for filename in config.SPAM_FILES:
            with open(filename, "r") as f:
                spam_list.extend([str_format.clean_string(l) for l in f])

        spamlines = len(spam_list)
        spam = "".join(spam_list)

        Template.__init__(self, "spam_panel_template", spam=spam, spamlines=spamlines)
开发者ID:dequis,项目名称:wakarimasen,代码行数:11,代码来源:staff_interface.py


示例18: render_template

def render_template(content, basename):
    """Render the template."""
    try:
        name = 'pan.tt'
        template = Template({'INCLUDE_PATH': os.path.join(os.path.dirname(__file__), 'tt')})
        output = template.process(name, {'content': content, 'basename': basename})
    except TemplateException as e:
        msg = "Failed to render template %s with data %s: %s." % (name, content, e)
        logger.error(msg)
        raise TemplateException('render', msg)
    return output
开发者ID:jouvin,项目名称:release,代码行数:11,代码来源:panhandler.py


示例19: show

    def show(self, http_handler, param, form=None):
	template = Template('base.html')
	template.setTemplate('CONTENT', 'control_test.html')
	template.setTemplate('INFO_BLOCK', 'admin_menue.html')
	template.setData('TEST', storage.userControlTestHtml(param[1]))

	report = storage.userReport(param[1])
	for key in report:
	    template.setData(key, report[key])

	self.answer(http_handler, template.show())
开发者ID:Letractively,项目名称:right-test,代码行数:11,代码来源:interface.py


示例20: make_admin_ban_panel

    def make_admin_ban_panel(self, ip=""):
        session = model.Session()
        table = model.admin

        sql = select(
            [
                model.activity.c.username,
                table.c.num,
                table.c.type,
                table.c.comment,
                table.c.ival1,
                table.c.ival2,
                table.c.sval1,
                table.c.total,
                table.c.expiration,
            ],
            from_obj=[
                table.outerjoin(
                    model.activity,
                    and_(table.c.num == model.activity.c.admin_id, table.c.type == model.activity.c.action),
                )
            ],
        ).order_by(table.c.type.asc(), table.c.num.asc())

        # TODO: We should be paginating, but the page needs to be
        # adjusted first.
        # res = model.Page(sql, self.page, self.perpage)

        query = session.execute(sql)
        bans = [dict(row.items()) for row in query]

        rowtype = 1
        prevtype = ""
        for row in bans:
            prevtype = row
            if prevtype != row["type"]:
                row["divider"] = 1

            # Alternate between values 1 and 2.
            rowtype ^= 0x3
            row["rowtype"] = rowtype

            if row["expiration"]:
                row["expirehuman"] = misc.make_date(row["expiration"])
            else:
                row["expirehuman"] = "Never"

            if row["total"] == "yes":
                row["browsingban"] = "No"
            else:
                row["browsingban"] = "Yes"

        Template.__init__(self, "ban_panel_template", bans=bans, ip=ip)
开发者ID:dequis,项目名称:wakarimasen,代码行数:53,代码来源:staff_interface.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python jinja2_engine.render函数代码示例发布时间:2022-05-27
下一篇:
Python template.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