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

Python utils.render_template函数代码示例

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

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



在下文中一共展示了render_template函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
                                  }
                                 )
开发者ID:claimat,项目名称:smart_ui_server,代码行数:30,代码来源:views.py


示例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)
开发者ID:atulg,项目名称:mils-secure,代码行数:32,代码来源:www.py


示例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)
开发者ID:internetarchive,项目名称:openlibrary,代码行数:29,代码来源:addbook.py


示例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})
开发者ID:M-CM,项目名称:indivo_ui_server,代码行数:35,代码来源:views.py


示例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', {})
开发者ID:elliotcohen,项目名称:indivo_ui_server,代码行数:26,代码来源:views.py


示例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))
开发者ID:newmediamedicine,项目名称:indivo_ui_server_1_0,代码行数:26,代码来源:views.py


示例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)
开发者ID:christhorpe,项目名称:bonnier-hackwall,代码行数:7,代码来源:main.py


示例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)
开发者ID:rajatgarg79,项目名称:openlibrary,代码行数:25,代码来源:borrow.py


示例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'])
开发者ID:sharmajai,项目名称:bloggart,代码行数:30,代码来源:static.py


示例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)
开发者ID:Mrudul,项目名称:clo-summit,代码行数:59,代码来源:www.py


示例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 
         })
开发者ID:claimat,项目名称:smart_ui_server,代码行数:58,代码来源:views.py


示例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})
开发者ID:newmediamedicine,项目名称:indivo_ui_server_1_0,代码行数:58,代码来源:views.py


示例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)
开发者ID:AAAStrix,项目名称:ctrl-class,代码行数:9,代码来源:homepage.py


示例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())
开发者ID:internetarchive,项目名称:openlibrary,代码行数:10,代码来源:addbook.py


示例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)
            )
开发者ID:CBIIT,项目名称:nci-webtools-dceg-classification,代码行数:55,代码来源:soccerProcessor.py


示例16: POST

 def POST(self):
     i = web.input(email='', irl='', comment='')
     fields = web.storage({
         'email': i.email,
         'irl': i.irl,
         'comment': i.comment,
         'sent': datetime.datetime.utcnow(),
         'browser': web.ctx.env.get('HTTP_USER_AGENT', '')
     })
     msg = render_template('email/spam_report', fields)
     web.sendmail(i.email, config.report_spam_address, msg.subject, str(msg))
     return render_template("contact/spam/sent")
开发者ID:artmedlar,项目名称:openlibrary,代码行数:12,代码来源:code.py


示例17: POST

 def POST(self):
     data = web.input()
     print(data)
     param = {'username':data.username,'password':data.password}
     ret = utils.db.users.find(param)
     print(ret.count())
     flag = True if ret.count()>0 else False 
     print(flag)
     if flag:
         return utils.render_template('main.html',msg=u'密码正确',**data)
     else:
         return utils.render_template('login.html',msg=u'密码错误',**data)
开发者ID:JasonZ321,项目名称:webpy-angular,代码行数:12,代码来源:main.py


示例18: showcase_index

def showcase_index(request):
   api = get_api()

   initial_app= request.GET.get('initial_app', "")

   ret = tokens_get_from_server(request, settings.PROXY_USER, settings.PROXY_PASSWORD)
   if not ret:
     return utils.render_template(LOGIN_PAGE, {'error': 'Could not find proxied user'})

   return utils.render_template('ui/showcase',
          { 'ACCOUNT_ID': settings.PROXY_USER,
            'INITIAL_APP': initial_app,
            'SMART_PASSTHROUGH_SERVER': passthrough_server })
开发者ID:claimat,项目名称:smart_ui_server,代码行数:13,代码来源:views.py


示例19: get

 def get(self):
     course = self.params.course
     projects = self.auth.user.projects_for_course(course)
     project_json = map(lambda p: p.as_json(include_relationships=True),
                        projects)
     tasks = self.auth.user.tasks_for_course(course)
     task_json = map(lambda t: t.as_json(), tasks)
     params = {
         'course': course,
         'project_json': project_json,
         'course_key': course.key.urlsafe(),
         'task_json': task_json
     }
     render_template(self, 'course.html', params)
开发者ID:AAAStrix,项目名称:ctrl-class,代码行数:14,代码来源:courses.py


示例20: __call__

 def __call__(self, ctx, mgr):
   source = resolve(self.source, ctx)
   dest = resolve(self.dest, ctx)
   if self.mode:
     ldest = '_%s'%source
     render_template(source, ldest, ctx)
     put(ldest, ldest)
     run('sudo mv %s %s'%(ldest, dest))
     run('sudo chmod %s %s'%(self.mode, dest))
     if self.owner:
       run('sudo chown %s %s'%(self.owner, dest))
     local('rm -f %s'%ldest)
   else:
     render_template(source, dest, ctx)
开发者ID:clozr,项目名称:smash,代码行数:14,代码来源:commands.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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