本文整理汇总了Python中utils.render_template函数的典型用法代码示例。如果您正苦于以下问题:Python render_template函数的具体用法?Python render_template怎么用?Python render_template使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了render_template函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_developer_account
def create_developer_account(request):
if request.method == "GET":
return utils.render_template('ui/create_developer_account',
{})
api = get_api()
username = request.POST.get("username")
password = request.POST.get("password")
given_name = request.POST.get("given_name")
family_name = request.POST.get("family_name")
department = request.POST.get("department")
role = request.POST.get("role")
data = {"account_id" : username, "password" : password,
"given_name" : given_name, "family_name" : family_name,
"department": department, "role" : role}
ret = api.call("POST", "/users/", options={'data': data})
if (ret == "account_exists"):
return utils.render_template('ui/create_developer_account',
{ 'error': "Account '%s' is already registered."%username })
return utils.render_template(LOGIN_PAGE,
{"error": "Account %s has been created. Please log in."%username,
"account" : username
}
)
示例2: get
def get(self):
auth_level = self.is_user_authorized()
if auth_level == models.AUTH_LEVEL_REGISTERED_USER:
self.redirect("/account/activate/reminder/")
elif auth_level == models.AUTH_LEVEL_ACTIVATED_USER:
today = datetime.utcnow()
year = self.request.get("year")
month = self.request.get("month")
if not year or not month:
year = today.year
month = today.month
else:
year = dec(year)
month = dec(month)
articles = Article.get_all_published_student_articles_for_month(year, month)
books = Book.get_latest(count=10)
response = render_template(
"blog_students.html",
year_list=models.BLOG_YEAR_LIST,
month_list=models.MONTH_LIST,
today=today,
requested_year=year,
requested_month=month,
articles=articles,
books=books,
)
self.response.out.write(response)
else:
response = render_template("index.html")
self.response.out.write(response)
示例3: POST
def POST(self, key):
i = web.input(v=None, _method="GET")
if spamcheck.is_spam():
return render_template("message.html",
"Oops",
'Something went wrong. Please try again later.')
recap = get_recaptcha()
if recap and not recap.validate():
return render_template("message.html",
'Recaptcha solution was incorrect',
'Please <a href="javascript:history.back()">go back</a> and try again.'
)
v = i.v and safeint(i.v, None)
work = web.ctx.site.get(key, v)
if work is None:
raise web.notfound()
try:
helper = SaveBookHelper(work, None)
helper.save(web.input())
add_flash_message("info", utils.get_message("flash_work_updated"))
raise web.seeother(work.url())
except (ClientException, ValidationException) as e:
add_flash_message('error', str(e))
return self.GET(key)
示例4: register
def register(request):
"""
http://localhost/change_password
Returns the register template (GET) or creates a new account (POST)
"""
if HTTP_METHOD_POST == request.method:
if not settings.REGISTRATION.get('enable', False):
return utils.render_template('ui/error', {'error_message': ErrorStr('Registration disabled'), 'error_status': 403})
# create the account
post = request.POST
set_primary = settings.REGISTRATION.get('set_primary_secret', 1)
user_hash = {'account_id': post.get('account_id'),
'contact_email': post.get('account_id'), # TODO:the contact_email key is not present in the register form for now, so use the account_id
'full_name': post.get('full_name'),
'primary_secret_p': set_primary,
'secondary_secret_p': settings.REGISTRATION.get('set_secondary_secret', 1)}
api = get_api()
res, content = api.account_create(body=user_hash)
# on success, forward to page according to the secrets that were or were not generated
if '200' == res['status']:
account_xml = content or '<root/>'
account = utils.parse_account_xml(account_xml)
account_id = account.get('id')
if not set_primary:
return utils.render_template(LOGIN_PAGE, {'MESSAGE': _('You have successfully registered.') + ' ' + _('After an administrator has approved your account you may login.'), 'SETTINGS': settings})
# display the secondary secret if there is one
has_secondary_secret = (None != account.get('secret') and len(account.get('secret')) > 0)
if has_secondary_secret:
return utils.render_template('ui/register', {'SETTINGS': settings, 'ACCOUNT_ID': account_id, 'SECONDARY': account.get('secret'), 'MESSAGE': _('You have successfully registered.') + ' ' + _('At the link sent to your email address, enter the following activation code:')})
return HttpResponseRedirect('/accounts/%s/send_secret/sent' % account_id)
return utils.render_template('ui/register', {'ERROR': ErrorStr((content or 'Setup failed')), 'SETTINGS': settings})
return utils.render_template('ui/register', {'SETTINGS': settings})
示例5: account_initialization_2
def account_initialization_2(request):
if request.method == HTTP_METHOD_POST:
account_id = request.path_info.split('/')[3]
username = request.POST['username'].lower().strip()
password = request.POST['pw1']
errors = {
'generic': 'There was a problem updating your data. Please try again. If you are unable to change your password please contact support.',
'collision': 'That username is already taken. Please enter different one.'
}
api = IndivoClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, settings.INDIVO_SERVER_LOCATION)
ret = api.add_auth_system(
account_id = account_id,
data = {'system':'password',
'username': username,
'password': password})
if ret.response['response_status'] == 200:
# everything's OK, log this person in, hard redirect to change location
tokens_get_from_server(request, username, password)
return HttpResponseRedirect('/')
elif ret.response['response_status'] == 400:
return utils.render_template('ui/account_init_2', {'ERROR': errors['collision']})
else:
return utils.render_template('ui/account_init_2', {'ERROR': errors['generic']})
else:
return utils.render_template('ui/account_init_2', {})
示例6: index
def index(request):
if tokens_p(request):
# get the realname here. we already have it in the js account model
api = get_api()
account_id = urllib.unquote(request.session['oauth_token_set']['account_id'])
try:
res = api.account_info(account_id = account_id)
except:
res = None
# got account info from the server
if res and res.response:
if 200 == res.response.get('response_status', 0):
e = ET.fromstring(res.response.get('response_data', '<xml/>'))
fullname = e.findtext('fullName')
return utils.render_template('ui/index', { 'ACCOUNT_ID': account_id,
'FULLNAME': fullname,
'ALLOW_ADDING_RECORDS': settings.ALLOW_ADDING_RECORDS,
'HIDE_GET_MORE_APPS': settings.HIDE_GET_MORE_APPS,
'HIDE_SHARING': settings.HIDE_SHARING })
# error
return_url = request.session.get('return_url', '/')
err_msg = res.response.get('response_data', '500: Unknown Error')
return utils.render_template(LOGIN_PAGE, {'ERROR': ErrorStr(err_msg), 'RETURN_URL': return_url, 'SETTINGS': settings})
return HttpResponseRedirect(reverse(login))
示例7: get
def get(self):
tweets = models.Tweet.all().search(self.request.get("q")).order('-created_at').fetch(1000)
template_values = {
"tweets": tweets,
"searchterm": self.request.get("q")
}
utils.render_template(self, "views/search.html", template_values)
示例8: GET
def GET(self, key):
if not is_admin():
return render_template('permission_denied', web.ctx.path, "Permission denied.")
edition = web.ctx.site.get(key)
if not edition:
raise web.notfound()
if edition.ocaid:
ebook_key = "ebooks/" + edition.ocaid
ebook = web.ctx.site.store.get(ebook_key) or {}
else:
ebook = None
i = web.input(updatestatus=None)
if i.updatestatus == 't':
edition.update_loan_status()
edition_loans = get_edition_loans(edition)
user_loans = []
user = accounts.get_current_user()
if user:
user_loans = get_loans(user)
return render_template("borrow_admin", edition, edition_loans, ebook, user_loans, web.ctx.ip)
示例9: get
def get(self, path):
if not path.startswith(config.url_prefix):
if path not in ROOT_ONLY_FILES:
self.error(404)
self.response.out.write(utils.render_template('404.html'))
return
else:
if config.url_prefix != '':
path = path[len(config.url_prefix):]# Strip off prefix
if path in ROOT_ONLY_FILES:# This lives at root
self.error(404)
self.response.out.write(utils.render_template('404.html'))
return
content = get(path)
if not content:
self.error(404)
self.response.out.write(utils.render_template('404.html'))
return
serve = True
if 'If-Modified-Since' in self.request.headers:
try:
last_seen = datetime.datetime.strptime(
self.request.headers['If-Modified-Since'].split(';')[0],# IE8 '; length=XXXX' as extra arg bug
HTTP_DATE_FMT)
if last_seen >= content.last_modified.replace(microsecond=0):
serve = False
except ValueError, e:
import logging
logging.error('StaticContentHandler in static.py, ValueError:' + self.request.headers['If-Modified-Since'])
示例10: get
def get(self):
from pickle import dumps
from ebs.merchant.api import get_ebs_request_parameters
dr = self.request.get('DR')
if dr:
billing_settings = BillingSettings.get_settings(deployment_mode=ebs_mode)
request = get_ebs_request_parameters(dr, billing_settings.secret_key)
response_code = request.get('ResponseCode', None)
response_message = request.get('ResponseMessage', 'There was no response from the billing system.')
group = self.session.get('participant_group')
group.transaction_response_id = str(request.get('PaymentID'))
group.transaction_response_code = str(response_code)
group.transaction_response_message = response_message
group.transaction_response_type = TRANSACTION_TYPE_EBS
group.transaction_response_amount = request.get('Amount', '0')
group.transaction_response = str(request)
group.transaction_response_object = db.Blob(dumps(request))
group.when_transaction_response_occurred = request.get('DateCreated')
group.put()
if response_code == 0:
# mark the participant group as paid.
message_title = 'Thank you for participating in the summit'
group_id = group.key().id()
logging.info('Payments for group: %s with %d processed.' % (group.title, group_id))
participants = self.session.get('participants')
if participants:
# Send email to all the participants about their attendance.
for participant in participants:
queue_mail_task(url='/worker/mail/thanks/registration/',
params=dict(
full_name=participant.full_name,
email = participant.email,
key=str(participant.key())
),
method='POST'
)
# Send email to the payer the invoice.
primary_participant = self.session.get('primary_participant')
queue_mail_task(url='/worker/mail/thanks/registration_payment/',
params=dict(
full_name=primary_participant.full_name,
email = primary_participant.email,
key=str(primary_participant.key()),
transaction_amount=group.transaction_response_amount
),
method='POST'
)
else:
message_title = 'There was an error processing your payment.'
response = render_template('thank_you.html', message_title=message_title, message_body=response_message + ''' Thank you for registering for the summit. An email confirming your payment and registration shall be sent to you shortly. In case you don't receive the email confirmation within 24 hours or you have any queries, please contact +91 22 66301060 / 22026166 from 10.30 AM IST to 6.30 AM IST''')
else:
response = render_template('thank_you.html', message_title="A problem occurred with the billing system.", message_body="We did not receive a proper response from the billing system.")
self.response.out.write(response)
示例11: token_login_index
def token_login_index(request, token):
request.session.flush()
api = get_api()
reqstore = request.GET
if (request.method == 'POST'): reqstore = request.POST
initial_app= reqstore.get('initial_app', "")
options = {'data': {'token':token}}
pin= reqstore.get('pin', "")
if pin:
options['data']['pin'] = pin
logintokenxml = api.call("GET", "/session/from_direct_url",
options=options)
if logintokenxml.startswith("Permission Denied"):
return utils.render_template("ui/need_pin",{})
logintoken= ET.fromstring(logintokenxml)
record_id = logintoken.find("Record").get("id")
record_name = logintoken.find("Record").get("label")
session_tokens = dict(urlparse.parse_qsl(logintoken.get("value")))
account_id = session_tokens['account_id']
request.session['oauth_token_set'] = session_tokens
request.session['account_id'] = urllib.unquote(account_id)
api = get_api(request)
account_id = urllib.unquote(request.session['oauth_token_set']['account_id'])
ret = api.account_info(account_id = account_id)
e = ET.fromstring(ret.response['response_data'])
fullname = e.findtext('givenName') +" "+ e.findtext('familyName')
target_template = "ui/proxy_index"
credentials = "''"
manifest = "''"
if (initial_app != ""):
target_template = "ui/single_app_view"
credentials = single_app_get_credentials(api, account_id, initial_app, record_id)
manifest = single_app_get_manifest(api, initial_app)
return utils.render_template(target_template,
{
'ACCOUNT_ID': session_tokens["account_id"],
'FULLNAME': fullname,
'PROXIED_RECORD_ID' : record_id,
'PROXIED_RECORD_NAME': record_name,
'INITIAL_APP': initial_app,
'SMART_PASSTHROUGH_SERVER': passthrough_server ,
'CREDENTIALS': credentials,
'MANIFEST': manifest
})
示例12: launch_app
def launch_app(request, app_id):
""" Entry point for a given app.
If the app does not exist (or another exception occurrs), will render /ui/error with the given error message. On
success, renders /ui/record_select after the user has logged in. Selecting a record will call the app's start_url.
"""
# make the user login first
login_url = "%s?return_url=%s" % (reverse(login), urllib.quote(request.get_full_path()))
account_id = urllib.unquote(request.session.get('account_id', ''))
if not account_id:
return HttpResponseRedirect(login_url)
# logged in, get information about the desired app
api = get_api() # gets the API with chrome credentials
ret = api.get_app_info(app_id=app_id)
res = ret.response if ret else {}
status = res.get('response_status', 500)
error_message = None
if 404 == status:
error_message = ErrorStr('No such App').str()
elif 200 != status:
error_message = ErrorStr(res.get('response_data', 'Error getting app info')).str()
if error_message is not None:
return utils.render_template('ui/error', {'error_message': error_message, 'error_status': status})
# success, find start URL template
xml = res.get('response_data', '<root />')
e = ET.fromstring(xml)
start_url = e.findtext('startURLTemplate')
# read account records
api.update_token(request.session.get('oauth_token_set')) # must be in app-credential-mode now
ret = api.read_records(account_id = account_id)
res = ret.response if ret else {}
status = res.get('response_status', 500)
if 404 == status:
error_message = ErrorStr('Unknown account').str()
elif 403 == status:
return HttpResponseRedirect(login_url)
elif 200 != status:
error_message = ErrorStr(res.get('response_data', 'Error getting account records')).str()
if error_message:
return utils.render_template('ui/error', {'error_message': error_message, 'error_status': status})
# parse records XML
records_xml = res.get('response_data', '<root/>')
records_extracted = [[r.get('id'), r.get('label')] for r in ET.fromstring(records_xml).findall('Record')]
records = []
for rec_id, rec_label in records_extracted:
rec_dict = { 'record_id': rec_id, 'carenet_id' : '' } # TODO: Carenets are not yet supported
records.append([rec_id, rec_label, _interpolate_url_template(start_url, rec_dict)])
return utils.render_template('ui/record_select', {'SETTINGS': settings, 'APP_ID': app_id, 'RECORD_LIST': records})
示例13: get
def get(self):
project_json = map(lambda x: x.as_json(include_relationships=True), self.auth.user.projects)
task_json = map(lambda x: x.as_json(), self.auth.user.tasks);
params = {
'courses': self.auth.user.courses,
'project_json': project_json,
'task_json': task_json
}
render_template(self, 'home.html', params)
示例14: GET
def GET(self):
if not self.has_permission():
return render_template("permission_denied", "/books/add", "Permission denied to add a book to Open Library.")
i = web.input(work=None, author=None)
work = i.work and web.ctx.site.get(i.work)
author = i.author and web.ctx.site.get(i.author)
return render_template('books/add', work=work, author=author, recaptcha=get_recaptcha())
示例15: consume
def consume(self, client, frame):
''' Consumes a frame from the queue '''
try:
# get configuration
mail_host = self.config['mail']['host']
# get parameters
params = json.loads(frame.body.decode())
self.logger.debug(params)
# call submit method of flask application
# generates output file and
self.logger.debug('processing input file: ' + params['file_id'])
self.process_file(params['file_id'], params['model_version'])
self.logger.debug('finished processing input file: ' + params['file_id'])
# send user results
self.logger.debug('sending results email to user')
send_mail(
host=mail_host,
sender='SOCcer<[email protected]>',
recipient=params['recipient'],
subject='SOCcer - Your file has been processed',
contents=render_template('templates/user_email.html', params)
)
except Exception as e:
# capture error information
error_info = {
'file_id': params['file_id'],
'params': json.dumps(params, indent=4),
'exception_info': format_exc(),
'process_output': getattr(e, 'output', 'None')
}
self.logger.exception(error_info)
# send user error email
self.logger.debug('sending error email to user')
send_mail(
host=mail_host,
sender='SOCcer<[email protected]>',
recipient=params['recipient'],
subject='SOCcer - An error occurred while processing your file',
contents=render_template('templates/user_error_email.html', params)
)
# send admin error email
self.logger.debug('sending error email to administrator')
send_mail(
host=mail_host,
sender='SOCcer<[email protected]>',
recipient=self.config['mail']['admin'],
subject='SOCcer - Exception occurred',
contents=render_template('templates/admin_error_email.html', error_info)
)