本文整理汇总了Python中turbogears.url函数的典型用法代码示例。如果您正苦于以下问题:Python url函数的具体用法?Python url怎么用?Python url使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了url函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: get_curso_actual
def get_curso_actual(self):
try:
contexto = SessionHelper().get_contexto_usuario()
return contexto.get_curso()
except SinCursosDisponibles as e:
if identity.has_permission(Permiso.admin):
raise redirect(url('/curso/new'))
else:
raise redirect(url('/error/%s' % e))
开发者ID:sercom,项目名称:sercom,代码行数:9,代码来源:controllers.py
示例17: test_basicurls
def test_basicurls(self):
testutil.createRequest("/")
self.failUnlessEqual("/foo", url("/foo"))
self.failUnlessEqual("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:thraxil,项目名称:gtreed,代码行数:9,代码来源:test_controllers.py
示例18: __init__
def __init__(self, current_page, pages, page_count, input_values,
limit, order, ordering, row_count, var_name):
self.var_name = var_name
self.pages = pages
self.limit = limit
self.page_count = page_count
self.current_page = current_page
self.input_values = input_values
self.order = order
self.ordering = ordering
self.row_count = row_count
self.first_item = page_count and ((current_page - 1) * limit + 1) or 0
self.last_item = min(current_page * limit, row_count)
self.reversed = ordering and ordering[0][0] == '-'
# If ordering is empty, don't add it.
input_values = {var_name + '_tgp_limit': limit}
if ordering:
input_values[var_name + '_tgp_ordering'] = ','.join(ordering)
self.input_values.update(input_values)
if current_page < page_count:
self.input_values.update({
var_name + '_tgp_no': current_page + 1,
var_name + '_tgp_limit': limit
})
self.href_next = turbogears.url(
cherrypy.request.path_info, self.input_values)
self.input_values.update({
var_name + '_tgp_no': 'last',
var_name + '_tgp_limit': limit
})
self.href_last = turbogears.url(
cherrypy.request.path_info, self.input_values)
else:
self.href_next = None
self.href_last = None
if current_page > 1:
self.input_values.update({
var_name + '_tgp_no': current_page - 1,
var_name + '_tgp_limit': limit
})
self.href_prev = turbogears.url(
cherrypy.request.path_info, self.input_values)
self.input_values.update({
var_name + '_tgp_no': 1,
var_name + '_tgp_limit': limit
})
self.href_first = turbogears.url(
cherrypy.request.path_info, self.input_values)
else:
self.href_prev = None
self.href_first = None
开发者ID:OnShift,项目名称:turbogears,代码行数:56,代码来源:paginate.py
示例19: deleteinnocentkill
def deleteinnocentkill(self,iid):
try:
eid=InnocentKill.get(iid).event.id
except SQLObjectNotFound:
flash("Error: you tried to delete an innocent kill that doesn't exist!")
raise redirect(url("/news"))
InnocentKill.delete(iid)
self.updatescores()
flash("Innocent Kill removed!")
raise redirect(url("/editevent/"+str(eid)))
开发者ID:m50d,项目名称:tumpire,代码行数:10,代码来源:controllers.py
示例20: default
def default(self,*args):
if len(args) != 1:
raise cherrypy.HTTPRedirect(turbogears.url("/panels"))
panelname=args[0]
print "panel renderer: "+panelname+"\n"
try:
panelDef = readPanelDefinition("../resources/paneldef/",panelname)
except PanelDefinitionException, e:
turbogears.flash(str(e))
raise cherrypy.HTTPRedirect(turbogears.url("/panels"))
开发者ID:AndyThirtover,项目名称:wb_gateway,代码行数:10,代码来源:PanelRenderer.py
注:本文中的turbogears.url函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论