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


Python turbogears.redirect函数代码示例

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


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

示例1: switchToCustomer

def switchToCustomer(customer, redirect_url=None, check_permission=False):
    if not identity.current.anonymous:
        current_user = identity.current.user
    else:
        current_user = None

    if current_user and customer == current_user.customer:
        if redirect_url:
            redirect(redirect_url)
        else:
            return

    if check_permission and current_user:
        if not current_user.hasModeratePermission():
            raise identity.IdentityFailure(
                "User %s was not authenticated to change the customer" % current_user.email_address
            )

    if check_permission:
        try:
            user = masterdb.User.selectBy(_customer=customer, deleted=False)[0]
            switchToUser(user, check_permission=check_permission)
        except:
            pass

    if redirect_url:
        redirect(redirect_url)
开发者ID:marqui678,项目名称:finalchance.Panopta,代码行数:27,代码来源:abstract_logic.py

示例2: install_options

 def install_options(self, distro_tree_id, **kwargs):
     try:
         distro_tree = DistroTree.by_id(distro_tree_id)
     except NoResultFound:
         flash(_(u'Invalid distro tree id %s') % distro_tree_id)
         redirect('.')
     if 'ks_meta' in kwargs:
         distro_tree.activity.append(DistroTreeActivity(
                 user=identity.current.user, service=u'WEBUI',
                 action=u'Changed', field_name=u'InstallOption:ks_meta',
                 old_value=distro_tree.ks_meta,
                 new_value=kwargs['ks_meta']))
         distro_tree.ks_meta = kwargs['ks_meta']
     if 'kernel_options' in kwargs:
         distro_tree.activity.append(DistroTreeActivity(
                 user=identity.current.user, service=u'WEBUI',
                 action=u'Changed', field_name=u'InstallOption:kernel_options',
                 old_value=distro_tree.kernel_options,
                 new_value=kwargs['kernel_options']))
         distro_tree.kernel_options = kwargs['kernel_options']
     if 'kernel_options_post' in kwargs:
         distro_tree.activity.append(DistroTreeActivity(
                 user=identity.current.user, service=u'WEBUI',
                 action=u'Changed', field_name=u'InstallOption:kernel_options_post',
                 old_value=distro_tree.kernel_options_post,
                 new_value=kwargs['kernel_options_post']))
         distro_tree.kernel_options_post = kwargs['kernel_options_post']
     flash(_(u'Updated install options'))
     redirect(str(distro_tree.id))
开发者ID:sibiaoluo,项目名称:beaker,代码行数:29,代码来源:distrotrees.py

示例3: view

    def view(self, groupname, order_by='username'):
        '''View group'''
        sort_map = { 'username': 'people_1.username',
            'creation': 'person_roles_creation',
            'approval': 'person_roles_approval',
            'role_status': 'person_roles_role_status',
            'role_type': 'person_roles_role_type',
            'sponsor': 'people_2.username',
            }
        username = turbogears.identity.current.user_name
        person = People.by_username(username)
        group = Groups.by_name(groupname)

        if not can_view_group(person, group):
            turbogears.flash(_("You cannot view '%s'") % group.name)
            turbogears.redirect('/group/list')
            return dict()

        # Also return information on who is not sponsored
        unsponsored = PersonRoles.query.join('group').join('member',
            aliased=True).outerjoin('sponsor', aliased=True).filter(
            and_(Groups.name==groupname,
                PersonRoles.role_status=='unapproved')).order_by(sort_map[order_by])
        unsponsored.json_props = {'PersonRoles': ['member']}
        members = PersonRoles.query.join('group').join('member', aliased=True).filter(
            People.username.like('%')
            ).outerjoin('sponsor', aliased=True).filter(
            Groups.name==groupname,
            ).order_by(sort_map[order_by])
        return dict(group=group, sponsor_queue=unsponsored,
            members=list(members))
开发者ID:chepioq,项目名称:fas,代码行数:31,代码来源:group.py

示例4: save_edit

 def save_edit(self, builds, notes, expiration=None, **kw):
     log.debug(repr(locals()))
     if len(builds) > 1:
         flash("Unable to add builds to an existing override")
         raise redirect("/override")
     builds = builds[0]
     if expiration:
         if datetime.utcnow() > expiration:
             flash("Cannot set an expiration in the past")
             if request_format() == "json":
                 return dict()
             raise redirect("/override/edit?build=" + builds)
     try:
         override = BuildRootOverride.byBuild(builds)
     except SQLObjectNotFound:
         flash("Cannot find override to edit %r" % builds)
         raise redirect("/override")
     override.notes = notes
     override.expiration = expiration
     if override.date_expired:
         log.debug("Retagging expired override: %s" % override.build)
         override.date_expired = None
         override.tag()
     flash("%s successfully edited" % builds)
     if request_format() == "json":
         return override.__json__()
     raise redirect("/override")
开发者ID:bitlord,项目名称:bodhi,代码行数:27,代码来源:overrides.py

示例5: user_update

    def user_update(self, id=None, **form_data):

        if not id:
            flash(_(u'Error accediendo al panel de control de usuario.'))
            raise redirect('/dashboard')

        if (identity.current.user_id == int(id)):

            usuario = val.validate_get(Usuario, 'usuario', id)

            if form_data['pwd_new'] and usuario.equals_password(form_data['pwd_old']):
                usuario.reset_password(form_data['pwd_new']) 
                msg = u'Contraseña modificada correctamente.'
            else:
                msg = u'No se modificó la contraseña'
            usuario.nombre = form_data['nombre']
            usuario.telefono = form_data['telefono']
            usuario.paginador = form_data['paginador']
            identity.current.user.paginador = usuario.paginador

            flash(u'Datos actualizados correctamente.\n'+msg)
            raise redirect('/dashboard')
        else:
            flash(_(u'Solo podés editar tus propios datos.'))
            raise redirect('/dashboard')
开发者ID:sercom,项目名称:sercom,代码行数:25,代码来源:controllers.py

示例6: create

    def create(self, **kwargs):
        if not kwargs.has_key('hostid'):
            turbogears.flash("Error: form did not provide hostid")
            raise redirect("/")
        hostid = kwargs['hostid']
        del kwargs['hostid']

        try:
            host = Host.get(hostid)
        except SQLObjectNotFound:
            turbogears.flash("Error: invalid hostid - foul play?")
            raise turbogears.redirect("/")
            
        try:
            category = Category.get(kwargs['category'])
        except SQLObjectNotFound:
            turbogears.flash("Error: invalid category - foul play?")
            raise turbogears.redirect("/host_category/0/new?hostid=%s" % hostid)
            
        del kwargs['category']

        try:
            hostcategory = HostCategory(host=host, category=category, **kwargs)
        except:
            turbogears.flash("Error: Host already has category %s.  Try again." % category.name)
            raise turbogears.redirect("/host_category/0/new?hostid=%s" % hostid)
        turbogears.flash("HostCategory created.")
        raise turbogears.redirect("/host_category/%s" % hostcategory.id)
开发者ID:squallsama,项目名称:mirrormanager-rfremix,代码行数:28,代码来源:controllers.py

示例7: join

 def join(self, show=None):
     if not show:
         turbogears.redirect('/show/list/')
     if identity.not_anonymous():
         identity.current.logout()
     show = Show.by_name(show)
     return dict(show=show)
开发者ID:0-T-0,项目名称:fas,代码行数:7,代码来源:__init__.py

示例8: delete

    def delete(self, id, tg_errors=None):
        if tg_errors:
            flash("Error: ID is not an integer.")
            raise redirect(request.headers.get("Referer", url("/")))

        try:
            album = Album.get(id)
        except:
            flash("Error: Album %d does not exist." % id)
            raise redirect(request.headers.get("Referer", url("/")))

        for photo in album.photos():
            fullname = os.path.join(config.get("photo_dir"), photo.filename)
            if os.path.exists(fullname):
                os.remove(fullname)

            try:
                photo.destroySelf()
            except:
                pass
                # log.debug(traceback.format_exc())

                # get rough page number to return to after delete.
        allalbums = list(Album.select(orderBy="-date"))
        idx = allalbums.index(album)
        page = (idx / 8) + 1

        album.destroySelf()
        flash("Album deleted successfully.")

        raise redirect(url("/?page=%d" % page))
开发者ID:clemej,项目名称:shutterbug,代码行数:31,代码来源:controllers.py

示例9: force_create

    def force_create(self, archivo, **kw):
        """Sube una entrega en lugar de un alumno"""
        instancia = kw['instancia']
        entregador = kw['entregador']
        archivo = archivo.file.read()
        try:
            zfile = ZipFile(StringIO(archivo), 'r')
        except BadZipfile:
            flash(_(u'El archivo ZIP no es válido'))
            raise redirect('force_new', kw)
        if zfile.testzip() is not None:
            flash(_(u'El archivo ZIP tiene errores de CRC'))
            raise redirect('force_new',kw)

        entregador_id = int(entregador)
        instancia = InstanciaDeEntrega.get(int(instancia))
        if instancia.ejercicio.grupal:
            entregador = Grupo.get(entregador_id)
        else:
            entregador = AlumnoInscripto.get(entregador_id)

        kw['instancia'] = instancia
        kw['archivos'] = archivo
        kw['entregador'] = entregador
        kw['observaciones'] = 'Entrega realizada manualmente por el docente %s' % identity.current.user.shortrepr()
        Entrega(**kw)
        flash('Se creo una nueva entrega')
        raise redirect('list')
开发者ID:sercom,项目名称:sercom,代码行数:28,代码来源:__init__.py

示例10: login

 def login(self,destination="",ticketid=""):
     if destination == "":
         destination = "/"
         
     if ticketid:
         # verify a wind ticket and log them in
         (success,uni,groups) = validate_wind_ticket(ticketid)
         if int(success) == 0:
             return "WIND authentication failed. Please Try Again."
         u = find_or_create_user(uni)
         if 'tlc.cunix.local:columbia.edu' in groups or \
            'staff.cunix.local:columbia.edu' in groups or \
            'tlcxml.cunix.local:columbia.edu' in groups:
             # it's good
             cherrypy.session['uni'] = uni
             set_cookie("candyman_auth",uni, path="/", expires=10 * 365 * 24 * 3600)
             raise redirect(destination)
         else:
             # they're not ccnmtl. kick them out
             return "This application is restricted to CCNMTL staff. See an admin if you need to get in."
     else:
         location = cherrypy.request.browser_url
         location = "/".join(location.rsplit("/")[:3]) + "/login"
         winddest = "%s?destination=%s" % (location,urllib.quote(destination))
         dest = "https://wind.columbia.edu/login?destination=%s&service=cnmtl_full_np" % winddest
         raise redirect(dest)
开发者ID:ccnmtl,项目名称:rollo,代码行数:26,代码来源:controllers.py

示例11: save

 def save(self, id=None, **kw):
     retention_tag = Tag(tag=kw['tag'], default=kw['default'],
             needs_product=kw['needs_product'],
             expire_in_days=kw['expire_in_days'])
     session.add(retention_tag)
     flash(_(u"OK"))
     redirect("./admin")
开发者ID:beaker-project,项目名称:beaker,代码行数:7,代码来源:retention_tags.py

示例12: newAssessment

	def newAssessment(self, level, childid = 0):
		if childid != 0:
			cherrypy.session['current_child'] = int(childid)
		if 'current_child' in cherrypy.session:		
			a = Assessment(childID=cherrypy.session['current_child'], ownerID=identity.current.user.id, level=level)
			raise redirect("/assessment?id=" + str(a.id))			
		raise redirect("/")
开发者ID:swsnider,项目名称:portfolio,代码行数:7,代码来源:assessment.py

示例13: _new_group

 def _new_group(self, group_id, display_name, group_name, ldap,
     root_password):
     user = identity.current.user
     if ldap and not user.is_admin():
         flash(_(u'Only admins can create LDAP groups'))
         redirect('.')
     try:
         Group.by_name(group_name)
     except NoResultFound:
         pass
     else:
         flash( _(u"Group %s already exists." % group_name) )
         redirect(".")
     group = Group()
     session.add(group)
     activity = Activity(user, u'WEBUI', u'Added', u'Group', u"", display_name)
     group.display_name = display_name
     group.group_name = group_name
     group.ldap = ldap
     if group.ldap:
         group.refresh_ldap_members()
     group.root_password = root_password
     if not ldap: # LDAP groups don't have owners
         group.user_group_assocs.append(UserGroup(user=user, is_owner=True))
         group.activity.append(GroupActivity(user, service=u'WEBUI',
             action=u'Added', field_name=u'User',
             old_value=None, new_value=user.user_name))
         group.activity.append(GroupActivity(user, service=u'WEBUI',
             action=u'Added', field_name=u'Owner',
             old_value=None, new_value=user.user_name))
     return group
开发者ID:sibiaoluo,项目名称:beaker,代码行数:31,代码来源:group.py

示例14: password

 def password(self, thepass, submit=None):
     char = Character.byName(turbogears.identity.current.user.character)
     thenode = Node.byHex(char.currentNode)
     found = False
     
     if thenode.deaduntil > today():
         flash("There's nobody there to talk to!")
         raise turbogears.redirect("/"+str(thenode.hex))
     
     for secret in thenode.secrets:
         if secret.password == thepass:
             found = True
             thenode.notifyWatchers(char, "whispered something to")
             inter = Interaction(character=char.name, day=today(), node=thenode.hex, item="PASSWORD_"+thepass)
             if secret.moneycost != 0 or secret.othercost != "":
                 raise turbogears.redirect("/req/"+str(secret.id))
             else: 
                 pwstring = thenode.name + " says: <blockquote>" + secret.passtext + "</blockquote>"
                 char.notify(thenode.name + " told you a secret:<br/><i>"+secret.passtext + "</i>")
                 thenode.notifyWatchers(char, " heard a secret from ")
     
     if (not found): 
         pwstring = thenode.name + " gives you a funny look."
     goback = "<a href='/"+str(thenode.hex)+"'>Go back to " + thenode.name + ".</a>"
     return dict(pwstring=pwstring, goback=goback)
开发者ID:ternus,项目名称:assassin-hexgrid,代码行数:25,代码来源:controllers.py

示例15: size

    def size(self, width, id, tg_errors=None):
        if tg_errors:
            if "width" in tg_errors.keys():
                idx = tg_errors.keys().index("width")
                flash("Error: Invalid photo size: %s" % tg_errors.values()[idx])
            else:
                flash("Error: Invalid photo ID.")
            raise redirect(request.headers.get("Referer", url("/")))

        try:
            photo = Photo.get(id)
        except:
            # log.debug(traceback.format_exc())
            flash("Error: Photo %d does not exist." % id)
            raise redirect(request.headers.get("Referer", "/"))

        try:
            fullpath = os.path.join(self.photo_dir, photo.filename)
            img = IMG.open(fullpath)
            if img.size[0] > img.size[1]:
                height = int(img.size[1] * (float(float(width) / float(img.size[0]))))
            else:
                height = width
                width = int(img.size[0] * (float(float(height) / float(img.size[1]))))

            img = self._orient(img)
            out = img.resize((width, height), IMG.ANTIALIAS)
            return out.tostring("jpeg", "RGB")
        except:
            # log.debug(traceback.format_exc())
            flash("Error resizing photo, sending full photo.")
            raise redirect(url("/static/photos/%s" % photo.filename))
开发者ID:clemej,项目名称:shutterbug,代码行数:32,代码来源:controllers.py


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