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


Python turbogears.url函数代码示例

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


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

示例1: 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

示例2: desconfirmar

    def desconfirmar(self, obj=None, **attrs):

        try:
            orcamento = Orcamento.get(obj)
        except AssertionError:
            flash('Orçamento não selecionado ou não existe.')
            raise redirect('/orcamento/listar')
        except ValueError:
            flash('Orçamento não selecionado ou não existe.')
            raise redirect('/orcamento/listar')
        except SQLObjectNotFound:
            flash('Orçamento não selecionado ou não existe.')
            raise redirect('/orcamento/listar')

        if orcamento.data_confirmacao:
            for item in orcamento.itens:
                item.subgrupoequipamento.reservas -= item.quantidade
            orcamento.data_confirmacao = None
            orcamento.data_prev_pagamento = None
            orcamento.data_pago = None
            flash("Orçamento desconfirmado.")
            raise redirect(url('/orcamento/editar/%s' % orcamento.id))
        else:
            flash("Este orçamento ainda não foi confirmado.")
            raise redirect(url('/orcamento/editar/%s' % orcamento.id))
开发者ID:allangarcia,项目名称:sisequip-tg1app,代码行数:25,代码来源:orcamento.py

示例3: test_basic_urls

 def test_basic_urls(self):
     testutil.create_request("/")
     assert "/foo" == url("/foo")
     assert "foo/bar" == url(["foo", "bar"])
     assert url("/foo", bar=1, baz=2) in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=2)) in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=None)) == "/foo?bar=1"
开发者ID:dikoufu,项目名称:turbogears,代码行数:7,代码来源:test_controllers.py

示例4: altera

 def altera(self, obj=None, **attrs):
     try:
         evento = Evento.get(obj)
     except Exception:
         flash(_(u"ERRO: O evento que você está tentando alterar não existe."))
         raise redirect(url('/evento'))
     titulo = _(u"Altera evento")
     subtitulo = _(u"")
     form = EventoForm(submit_text=u"Salvar")
     if attrs:
         @validate(form)
         def get_errors(self, tg_errors=None, **data):
             return tg_errors, data
         tg_errors, data = get_errors(self, **attrs)
         if not tg_errors:
             try:
                 evento.set(
                     processoID = data['processoID'],
                     data = data['data'],
                     descricao = data['descricao'],
                     archive = data['archive'],
                     ownerID=identity.current.user.id,
                     )
                 flash(_(u"OK: Parte processo alterada."))
             except Exception:
                 flash(_(u"ERRO: Houve problemas ao alterar no banco de dados."))
             raise redirect(url('/evento'))
         else:
             flash(_("ATENÇÃO: Problemas no formulário, verifique as mensagens."))
     else:
         data = evento
     return dict(acoes=self._get_acoes(),titulo=titulo,subtitulo=subtitulo,select="Eventos",
                 form=form,data=data)
开发者ID:allangarcia,项目名称:sisproc-tg1app,代码行数:33,代码来源:evento.py

示例5: 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

示例6: save_upgrade_registration

    def save_upgrade_registration(self, **form_data):
        ERROR_CRED_INVALIDAS =_(u'No fue posible completar la operación. Revisar que el padrón y el password sean correctos.')
        ERROR_FORMAT =_(u'No fue posible completar la operación. El padrón se compone solamente de números.')

        curso = Curso.get(form_data['curso'])
        if not curso.inscripcion_abierta:
            flash('La inscripción al curso elegido se encuentra cerrada.')
            raise redirect(url('/'))

        try:
            if not form_data['padron'].isdigit():
                error_msg = ERROR_FORMAT
            else:
                alumno = Alumno.by_padron(form_data['padron'])
                if alumno.equals_password(form_data['password']):
                    if not curso in alumno.cursos:
                        curso.add_alumno(alumno)
                        flash(_(u'La inscripción ha sido exitosa.'))
                    else:
                        flash(_(u'¡Ya estabas inscripto a este curso!'))
                    raise redirect(url('/'))

                else:
                    error_msg = ERROR_CRED_INVALIDAS
        except SQLObjectNotFound:
            error_msg = ERROR_CRED_INVALIDAS
        except DuplicateEntryError, e:
	    error_msg = _(u'Ya estás registrado en el curso %s.' % curso)
开发者ID:sercom,项目名称:sercom,代码行数:28,代码来源:controllers.py

示例7: save

    def save(self, task_rpm, *args, **kw):
        """
        TurboGears method to upload task rpm package
        """
        rpm_path = Task.get_rpm_path(task_rpm.filename)

        if not task_rpm.filename:
            flash(_(u'No task RPM specified'))
            redirect(url("./new"))

        # we do it here, since we do not want to proceed
        # any further
        if len(task_rpm.filename) > 255:
            flash(_(u"Task RPM name should be <= 255 characters"))
            redirect(url("./new"))

        if os.path.exists("%s" % rpm_path):
            flash(_(u'Failed to import because we already have %s' % 
                                                     task_rpm.filename ))
            redirect(url("./new"))

        try:
            def write_data(f):
                siphon(task_rpm.file, f)
            task = Task.update_task(task_rpm.filename, write_data)
        except Exception, err:
            session.rollback()
            log.exception('Failed to import %s', task_rpm.filename)
            flash(_(u'Failed to import task: %s' % err))
            redirect(url("./new"))
开发者ID:omps,项目名称:beaker,代码行数:30,代码来源:tasks.py

示例8: get_package_updates

    def get_package_updates(self, package, release):
        entries = []
        pkg = Package.byName(package)
        base = config.get('base_address')
        for i, update in enumerate(pkg.updates()):
            delta = datetime.utcnow() - update.date_submitted
            if delta and delta.days > config.get('feeds.num_days_to_show'):
                if len(entries) >= config.get('feeds.max_entries'):
                    break

            if release and not update.release.name == release:
                continue

            entries.append({
                'id'        : base + url(update.get_url()),
                'summary'   : update.notes,
                'link'      : base + url(update.get_url()),
                'published' : update.date_submitted,
                'updated'   : update.date_submitted,
                'title'     : update.title,
            })
        return dict(
                title = 'Latest Updates for %s' % package,
                subtitle = "",
                link = config.get('base_address') + url('/'),
                entries = entries
        )
开发者ID:docent-net,项目名称:bodhi,代码行数:27,代码来源:rss.py

示例9: get_latest_comments

    def get_latest_comments(self, user=None):
        entries = []
        if user:
            comments = Comment.select(Comment.q.author == user,
                    orderBy=Comment.q.timestamp).reversed()
        else:
            comments = Comment.select(Comment.q.author != 'bodhi',
                    orderBy=Comment.q.timestamp).reversed()
        for comment in comments:
            delta = datetime.utcnow() - comment.update.date_submitted
            if delta and delta.days > config.get('feeds.num_days_to_show'):
                if len(entries) >= config.get('feeds.max_entries'):
                    break

            entries.append({
                'id'        : config.get('base_address') + \
                              url(comment.update.get_url()),
                'summary'   : comment.text,
                'published' : comment.timestamp,
                'link'      : config.get('base_address') + \
                              url(comment.update.get_url()),
                              'title'     : "[%s] [%s] [%d]" % (
                                  comment.update.title, comment.author,
                                  comment.karma)
            })
        return dict(
                title = 'Latest Comments',
                subtitle = "",
                link = config.get('base_address') + url('/'),
                entries = entries,
        )
开发者ID:docent-net,项目名称:bodhi,代码行数:31,代码来源:rss.py

示例10: saveparticipant

    def saveparticipant(self,new,eid,player,pseudonym="",id=0,submit=""):
         if(new):
	     try:
	         for q in Event.get(eid).participants:
	             if(q.player.user_name==player):
		         flash("Error: %s is already a participant in this event"%player)
		         raise redirect(url("/editevent/"+str(eid)))
	         p=Participant(event=Event.get(eid),player=User.by_user_name(player),pseudonym=Pseudonym.byName(player))
             except SQLObjectNotFound:
	         flash("Error: Tried to add a participant to a nonexistent event")
		 raise redirect(url("/news"))
	 else:
	     try:
	         p=Participant.get(id)
             except SQLObjectNotFound:
	         flash("Error: Tried to edit a nonexistent participant")
		 raise redirect(url("/news"))
	     try:
	         p.player=User.by_user_name(player)
  	         p.pseudonym=Pseudonym.byName(pseudonym)
	     except SQLObjectNotFound:
	         flash("Error: Tried to change pseudonym to one that doesn't exist, or change pseudonym for a player that doesn't exist")
		 raise redirect(url("/news"))
	 flash("Participant updated!")
	 raise redirect(url("/editevent/"+str(eid)))
开发者ID:m50d,项目名称:tumpire,代码行数:25,代码来源:controllers.py

示例11: saveuser

    def saveuser(self,oldname,name,address,college,water,notes,password,email,adjustment):
        if(oldname):
		try:
			u=User.by_user_name(oldname)
		except SQLObjectNotFound:
			flash("Error: Tried to edit a nonexistent player")
			raise redirect(url("/scoresname"))
		#u.user_name=name #don't give too much opportunity to break things
		u.address=address
		u.college=college
		u.water=water
		u.notes=notes
		if(password):
			u.password=password
		u.email_address=email
		if(adjustment!=u.adjustment and not identity.in_group('admin')):
			flash("Error: Tried to change a score adjustment while not umpire")
			raise redirect(url('/scoresname'))
		u.adjustment=adjustment
	else:
		u=User(user_name=name,address=address,college=college,water=water,notes=notes,password=password,email_address=email,score=0.0,adjustment=adjustment)
		p=Pseudonym(name=name,player=u)
	self.updatescores()
	flash("Player updated!")
	raise redirect(url("/scoresname"))
开发者ID:m50d,项目名称:tumpire,代码行数:25,代码来源:controllers.py

示例12: login

    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            if identity.in_group("issuer"):
                forward_url= url("issuer")
            elif identity.in_group("bidder"):
                forward_url= url("bidder")
            elif identity.in_group("admin"):
                forward_url = url("admin")           
            raise redirect(forward_url)

        forward_url=None
        previous_url= request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= request.headers.get("Referer", "/")
            
        response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)
开发者ID:tombs,项目名称:Python-Code,代码行数:30,代码来源:root.py

示例13: deleteevent

    def deleteevent(self,id):
        try:
	    Event.delete(id)
	    flash("Event deleted!")
	    raise redirect(url("/news"))
        except SQLObjectNotFound:
	    flash("Error: Tried to delete an event that doesn't exist")
	    raise redirect(url("/news"))
开发者ID:m50d,项目名称:tumpire,代码行数:8,代码来源:controllers.py

示例14: test_approots

 def test_approots(self):
     testutil.create_request("/subthing/")
     assert cherrypy.response.status.startswith("200")
     assert url("foo") == "foo"
     assert url("/foo") == "/subthing/foo"
     testutil.create_request("/nosubthing/")
     assert cherrypy.response.status.startswith("404")
     assert url("foo") == "foo"
     assert url("/foo") == "/foo"
开发者ID:dikoufu,项目名称:turbogears,代码行数:9,代码来源:test_controllers.py

示例15: test_basic_urls

 def test_basic_urls(self):
     self.app.get("/")
     assert "/foo" == url("/foo")
     assert "foo/bar" == url(["foo", "bar"])
     assert url("/foo", bar=1, baz=2) in \
         ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=2)) in \
         ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"]
     assert url("/foo", dict(bar=1, baz=None)) == "/foo?bar=1"
开发者ID:marqui678,项目名称:finalchance.Panopta,代码行数:9,代码来源:test_controllers.py


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