本文整理汇总了Python中template.template函数的典型用法代码示例。如果您正苦于以下问题:Python template函数的具体用法?Python template怎么用?Python template使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了template函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
def get(self, tab='info'):
params = {}
params['bigboard'] = self.request.get('bigboard')
if tab == 'info':
feed = []
for msg in Message.query(Message.show_in_day_of == True).order(-Message.added).fetch(limit=20):
feed.append({"date": msg.added, "type": "message", "message": msg})
for post in Post.query(Post.feed == 'twitter/user/HackAtBrown', Post.is_reply == False).order(-Post.date).fetch(limit=20):
feed.append({"date": post.date, "type": "tweet", "tweet": post})
feed.sort(key=lambda x: x['date'], reverse=True)
params['feed'] = feed[:min(len(feed), 20)]
elif tab == 'requests':
def request_to_dict(req):
return {
"name": req.requester.get().name if req.requester else None,
"issue": req.issue,
"tags": req.tags,
"location": req.location,
"time": req.created
}
params['requests'] = map(request_to_dict, MentorRequest.query().order(-MentorRequest.created).fetch(limit=100))
content = template("day_of/{0}.html".format(tab), params) # TODO: security-ish stuff
if self.request.get('ajax'):
self.response.write(content)
else:
index_params = {
"tab": tab,
"tab_content": content,
"bigboard": self.request.get('bigboard')
}
self.response.write(template("day_of/index.html", index_params))
示例2: __add_all_templates__
def __add_all_templates__(self) :
#nominal
if self.name.find('DATA')!=-1 or self.name.find('JES') != -1 or self.name.find('JER') != -1 :
self.all_templates.append(template(self.name,self.formatted_name))
else :
self.all_templates.append(template(self.name,self.formatted_name+', nominal'))
if self.name.find('JES') == -1 and self.name.find('JER') == -1 :
if self.step == 'initial' :
#simple systematics up/down
for i in range(len(self.simple_systematic_reweights_arrays)/3) :
sysname = simple_systematics_dists[i]
self.all_templates.append(template(self.name+'__'+sysname+'__up',self.formatted_name+', '+sysname+' up'))
self.all_templates.append(template(self.name+'__'+sysname+'__down',self.formatted_name+', '+sysname+' down'))
#PDF systematics up/down
for i in range(1,(len(self.pdf_reweight_array)-1)/2) :
self.all_templates.append(template(self.name+'__pdf_lambda_'+str(i)+'__up',self.formatted_name+', PDF lambda'+str(i)+' up'))
self.all_templates.append(template(self.name+'__pdf_lambda_'+str(i)+'__down',self.formatted_name+', PDF lambda'+str(i)+' down'))
if self.step != 'final' :
#fit parameters up/down
for i in range(len(self.fit_parameter_names)) :
self.all_templates.append(template(self.name+'__par_'+self.fit_parameter_names[i]+'__up',self.formatted_name+', '+self.fit_parameter_names[i]+' up'))
self.all_templates.append(template(self.name+'__par_'+self.fit_parameter_names[i]+'__down',self.formatted_name+', '+self.fit_parameter_names[i]+' down'))
#NTMJ fit parameters up/down
if self.name.find('ntmj')!=-1 :
self.all_templates.append(template(self.name+'__fit__up',self.formatted_name+', NTMJ fit error up'))
self.all_templates.append(template(self.name+'__fit__down',self.formatted_name+', NTMJ fit error down'))
示例3: run
def run():
defaultmech = "%s/mapping/cb05cl_ae6_aq.csv" % os.path.dirname(__file__)
parser = ArgumentParser(description = "Usage: %prog [-tq] \n"+(" "*16)+" [-i <init name>] [-f <final name>] <yamlfile>")
parser.add_argument("-t", "--template", dest = "template", action = "store_true", default = False, help="Output template on standard out (configurable with -m and -c")
parser.add_argument("-v", "--verbose", dest = "verbose", action = "count", default = 0, help = "extra output for debugging")
paths = glob(os.path.join(os.path.dirname(__file__), 'mapping', '*_*.csv'))
mechanisms = ', '.join(['_'.join(path.split('/')[-1].split('_')[:])[:-4] for path in paths])
parser.add_argument("-c", "--configuration", dest="configuration", default = None,
help = "Chemical mechanisms: %s (for use with -t)" % mechanisms)
parser.add_argument('configfile')
options = parser.parse_args()
args = [options.configfile]
if options.template:
from template import template
if options.configuration is None:
warn("Using default mechanism: %s" % defaultmech)
options.configuration = defaultmech
else:
if os.path.exists(options.configuration):
pass
else:
options.configuration = "%s/mapping/%s.csv" % (os.path.dirname(__file__), options.configuration)
if not os.path.exists(options.configuration):
raise IOError('Cannot find file %s; must be either you own file or in %s' % (options.configuration, mechanisms))
print template(options.configuration)
parser.exit()
if len(args)<1:
parser.error(msg="Requires a yaml file as an argument. For a template use the -t option. The template will be output to the stdout.")
else:
yamlpath=args[0]
from load import loader
from process import process
outf = process(config = loader(yamlpath), verbose = options.verbose)
示例4: creatConfig
def creatConfig(self):
values = {
'memory' : str(self.memory),
# 'memory' : str(self.memory * 1024),
'num_cpu' : str(self.num_cpu),
'name' : self.vm_name,
'image_path' : self.vm_path + self.image_name
}
config_path = self.vm_path+self.vm_name+'.cfg'
template('ubuntu_xen.mustache', values, config_path)
示例5: send_to_email
def send_to_email(self, email, template_args={}):
# does the actual work of sending
emails = [email]
assert self.email_subject, "No email subject provided. Is email unchecked?"
if self.email_from_template:
html = template("emails/" + self.email_html + ".html", template_args)
else:
html = template_string(self.email_html, template_args)
html = template("emails/generic.html", dict({"content": html}.items() + template_args.items()))
subject = template_string(self.email_subject, template_args)
send_email(html, subject, emails)
示例6: post
def post(self):
keys = ['name', 'role', 'email', 'phone', 'availability', 'tags', 'details']
try:
mentor = Mentor()
for key in keys:
val = self.request.get(key)
if key == 'tags':
val = [tag.strip().lower() for tag in val.split(',')]
setattr(mentor, key, val)
mentor.put()
first_name = mentor.name.split(' ')[0] if mentor.name else 'mentor'
self.response.write(template("mentor_signup.html", {"show_confirmation": True, "first_name": first_name}))
except datastore_errors.BadValueError as e:
print "MENTOR SIGNUP ERROR: {0}".format(e)
self.response.write(template("mentor_signup.html", {"error": "There's an invalid or missing field on your form!"}))
示例7: getTemplateObj
def getTemplateObj(ip,servername):
try:
t = template.template(state.game,state.language,servername,ip=ip)
allTemplateObj[servername] = t
#print ip,servername
except Exception,e1:
error[servername] = str(e1)
示例8: post
def post(self):
if not isAdmin(): return self.redirect('/')
audience = None if self.request.get('audience') == '' else self.request.get('audience')
message = Message(audience=audience)
if self.request.get('email'):
message.email_subject = self.request.get('email-subject')
if self.request.get('email-name'):
message.email_from_template = True
message.email_html = self.request.get('email-name')
else:
message.email_html = self.request.get('email-html')
if self.request.get('sms'):
message.sms_text = self.request.get('sms-text')
if self.request.get('show-in-day-of'):
message.day_of_html = self.request.get('day-of-html')
message.show_in_day_of = True
if self.request.get('test'):
recip = self.request.get('test-recipient')
if '@' in recip:
message.send_to_email(recip)
self.response.write("Sent email")
elif len(recip) > 0:
message.send_to_phone(recip)
self.response.write("Sent SMS")
else:
message.put()
message.kick_off()
self.response.write(template("messages_dashboard.html", {"status": "Sent!"}))
示例9: post
def post(self):
hacker = Hacker()
hacker.ip = self.request.remote_addr
for key in hacker_keys:
vals = self.request.get_all(key)
val =','.join(vals)
try:
setattr(hacker, key, val)
except datastore_errors.BadValueError as err:
return self.response.write(json.dumps({"success":False, "msg" : "Register", "field" : str(err.args[0]), "newURL" : blobstore.create_upload_url('/register')}))
if Hacker.query(Hacker.email == hacker.email).count() > 0:
return self.response.write(json.dumps({"success":False, "msg": "Email Already Registered!"}))
resume_files = self.get_uploads('resume')
if len(resume_files) > 0:
hacker.resume = resume_files[0].key()
hacker.secret = generate_secret_for_hacker_with_email(hacker.email)
# try:
# email_html = template("emails/confirm_registration.html", {"name": hacker.name.split(" ")[0], "hacker": hacker})
# send_email(recipients=[hacker.email], subject="You've applied to [email protected]!", html=email_html)
# hacker.post_registration_email_sent_date = datetime.datetime.now()
# except Exception, e:
# pass
hacker.put()
name = hacker.name.title().split(" ")[0] # TODO: make it better
confirmation_html = template("post_registration_splash.html", {"name": name, "secret": hacker.secret})
self.response.write(json.dumps({"success": True, "replace_splash_with_html": confirmation_html}))
示例10: get
def get(self):
variables = {
"registration_status": "registration_open"
}
variables['registration_post_url'] = blobstore.create_upload_url('/register')
self.response.write(template("index.html", variables))
示例11: get
def get(self, secret):
hacker = getHacker(secret)
if hacker is None:
self.redirect('/')
# this shouldn't silently fail. we should make a 404
return
status = hacker.computeStatus()
resumeFileName = ""
receiptsFileNames = ""
if hacker.resume:
resumeFileName = hackerFiles.getFileName(hacker.resume)
if hacker.receipts and hacker.receipts[0] != None:
receiptsFileNames = hackerFiles.getFileNames(hacker.receipts)
name = hacker.name.split(" ")[0] # TODO: make it better
self.response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, pre-check=0, post-check=0"
self.response.headers["Pragma"] = "no-cache"
self.response.headers["Expires"] = "0"
deadline = 7
deadlineFull = "2/07/2015"
if hacker.deadline:
deadline = (hacker.deadline - datetime.datetime.now()).days
deadlineFull = hacker.deadline.strftime("%m.%d.%y")
if hacker.rsvpd != True and deadline < 0:
registration.expire_hacker(hacker)
self.redirect('/')
return
self.response.write(template.template("hacker_page.html", {"hacker": hacker, "status": status, "name": name, "resumeFileName" : resumeFileName, "receiptsFileNames" : receiptsFileNames, "deadline": deadline, "deadlineFull": deadlineFull}))
示例12: create_template
def create_template(self, height, width):
#Initialiser les minima et maxima
min_x = height
min_y = width
max_x = 0
max_y = 0
color = ''
for b in self.xbubbles:
color = b['color']
if min_x > b['x']:
min_x = b['x']
if min_y > b['y']:
min_y = b['y']
if max_x < b['x']:
max_x = b['x']
if max_y < b['y']:
max_y = b['y']
# Projection
for b in self.xbubbles:
b['x'] -= min_x
b['y'] -= min_y
temp = template(False, width, height, '', 'blue')
# Ecriture du template
for b in self.xbubbles:
w = bubble()
w.color = 'blue'
temp[b['x']][b['y']] = w
return temp
示例13: get
def get(self):
if not onTeam(): return self.redirect('/')
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
return
def formatter(person):
JSON = {}
key = getattr(person, 'key')
JSON['id'] = key.urlsafe()
JSON['kind'] = key.kind()
JSON.update(person.asDict(['email', 'name', 'checked_in']))
return JSON
from models import Volunteer, Rep
source = map(formatter, Hacker.query(Hacker.checked_in == False).fetch())
source += map(formatter, Rep.query(Rep.checked_in == False).fetch())
source += map(formatter, Volunteer.query(Volunteer.checked_in == False).fetch())
total_checked_in = getTotal()
session = models.CheckInSession()
session.user = user.email()
session.put()
token = channel.create_channel(session.key.urlsafe())
self.response.write(template("checkin.html", {"source" : json.dumps(source), 'total_checked_in' : total_checked_in, 'token' : token}))
示例14: put
def put(servername,ip,method):
newserverTemplate = template.template(state.game,state.language,servername,ip=ip)
check = False
for i in range(10):
try:
if method.strip() == "sql":
newserverTemplate.updateServerSql()
check = True
if method.strip() == "common":
newserverTemplate.updateServerLib()
check = True
if method.strip() == "gametemplate":
newserverTemplate.updateServerConf()
check = True
if method.strip() == "properties":
newserverTemplate.updateServerProperties()
check = True
if method.strip() == "www":
newserverTemplate.updateServerWww()
check = True
if method.strip() == "nginx":
newserverTemplate.updateServerNginxConf()
check = True
break
except:
pass
if not check:
errorAdd(servername," %s模板生成失败! "%method)
示例15: expire_hacker
def expire_hacker(hacker):
if hacker.rsvpd == True or hacker.admitted_email_sent_date == None:
#hacker has rsvp'd or was never accepted
return
print "Expiring " + hacker.email + " with admit date: " + str(hacker.admitted_email_sent_date)
email = template("emails/admittance_expired.html", {"name":hacker.name.split(" ")[0]})
send_email(recipients=[hacker.email], html=email, subject="You didn't RSVP to [email protected] in time...")
deletedHacker.createDeletedHacker(hacker, "expired")
hacker.key.delete()