本文整理汇总了Python中tg.url函数的典型用法代码示例。如果您正苦于以下问题:Python url函数的具体用法?Python url怎么用?Python url使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了url函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_one
def get_one(self, idpds):
# pylint:disable-msg=C0111,R0201
idhost = get_parent_id("hosts")
pds = get_pds(idpds, idhost)
result = {
"id": pds.idperfdatasource,
"href": tg.url("/api/v%s/hosts/%s/perfdatasources/%s"
% (self.apiver, pds.host.idhost, pds.idperfdatasource)),
"host": {
"id": pds.host.idhost,
"name": pds.host.name,
"href": tg.url("/api/v%s/hosts/%s" % (self.apiver, pds.host.idhost)),
},
"name": pds.name,
"type": pds.type,
"label": pds.label,
"factor": pds.factor,
"max": pds.max,
}
graphs = []
for graph in pds.graphs:
graphs.append({
"id": graph.idgraph,
"href": tg.url("/api/v%s/graphs/%s" % (self.apiver, graph.idgraph)),
"name": graph.name,
})
result["graphs"] = graphs
return dict(pds=result)
示例2: post_logout
def post_logout(self, came_from=url('/')):
"""
Redirect the user to the initially requested page on logout and say
goodbye as well.
"""
redirect(url('/login'))
示例3: document
def document(self, *args, **kwargs):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
if not resp:
log.info('ErrorDocument without original_response')
redirect(url('/'))
code = request.params.get('code', resp.status_int)
status = resp.status or code
req = request.environ.get('pylons.original_request')
if not req:
log.info('ErrorDocument without original_request')
redirect(url('/'))
log.info('Error %s, Request: %s %s, Referer: %s', status,
req.method, req.url, req.referer)
message = messages.get(code, default_message)
if req.referer:
message += ('<p><a href="%s" class="btn btn-inverse">'
'<i class="icon-arrow-left icon-white"></i>'
' Go back</a></p>' % req.referer)
values = dict(prefix=request.environ.get('SCRIPT_NAME', ''),
status=status, code=code,
message=request.params.get('message', message))
return values
示例4: login
def login(self, came_from=url('/')):
"""Start the user login."""
login_counter = request.environ['repoze.who.logins']
if login_counter > 0:
flash(_('Wrong credentials'), 'warning')
return dict(page='login', login_counter=str(login_counter),
came_from=url('/proyectos'))
示例5: assign_project
def assign_project(self, site_id, *a, **kw):
errors = _h.get_validation_errors()
s = DBSession.query(Site).filter_by(id=site_id).first()
p = DBSession.query(Project).filter_by(id=kw.get('project_id', None))\
.first()
all_p = DBSession.query(Project).all()
_h.protect_obj(s)
_h.protect_obj(p)
if not s:
raise HTTPNotFound
if not p:
raise HTTPNotFound
all_projects = [x for x in all_p if x not in s.projects]
if errors:
transaction.doom()
return dict(errors=errors, site=s, all_projects=all_projects)
_s_label = s.label
s.projects.append(p)
if kw.get('sync_path', None):
self._add_site_sync_path(s.id, p.id, kw['sync_path'])
else:
transaction.doom()
flash(_('Site sync path required for each project.'), 'warning')
redirect(url("/site/%s/edit#mirrored_projects" % _s_label))
transaction.commit()
redirect(url("/site/%s/edit#projects" % _s_label))
示例6: test_url_sop
def test_url_sop(self):
from tg import url
eq_("/foo", url("/foo"))
u = url("/foo", bar=1, baz=2)
assert u in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"], u
示例7: new_projects
def new_projects(self, **kwargs):
start_dt = kwargs.pop('start-dt', '')
end_dt = kwargs.pop('end-dt', '')
try:
start_dt = datetime.strptime(start_dt, '%Y/%m/%d %H:%M:%S')
except ValueError:
start_dt = datetime.utcnow() + timedelta(days=1)
try:
end_dt = datetime.strptime(end_dt, '%Y/%m/%d %H:%M:%S')
except ValueError:
end_dt = start_dt - timedelta(days=3) if not end_dt else end_dt
start = bson.ObjectId.from_datetime(start_dt)
end = bson.ObjectId.from_datetime(end_dt)
nb = M.Neighborhood.query.get(name='Users')
projects = (M.Project.query.find({
'neighborhood_id': {'$ne': nb._id},
'deleted': False,
'_id': {'$lt': start, '$gt': end},
}).sort('_id', -1))
step = start_dt - end_dt
params = request.params.copy()
params['start-dt'] = (start_dt + step).strftime('%Y/%m/%d %H:%M:%S')
params['end-dt'] = (end_dt + step).strftime('%Y/%m/%d %H:%M:%S')
newer_url = tg.url(params=params).lstrip('/')
params['start-dt'] = (start_dt - step).strftime('%Y/%m/%d %H:%M:%S')
params['end-dt'] = (end_dt - step).strftime('%Y/%m/%d %H:%M:%S')
older_url = tg.url(params=params).lstrip('/')
return {
'projects': projects,
'newer_url': newer_url,
'older_url': older_url,
'window_start': start_dt,
'window_end': end_dt,
}
示例8: put_delete
def put_delete(self, item_id):
require_current_user_is_owner(int(item_id))
# TODO - CHECK RIGHTS
item_id = int(item_id)
content_api = ContentApi(tmpl_context.current_user)
item = content_api.get_one(item_id, self._item_type, tmpl_context.workspace)
try:
next_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
tmpl_context.folder_id,
tmpl_context.thread_id)
undo_url = tg.url('/workspaces/{}/folders/{}/threads/{}/comments/{}/put_delete_undo').format(tmpl_context.workspace_id,
tmpl_context.folder_id,
tmpl_context.thread_id,
item_id)
msg = _('{} deleted. <a class="alert-link" href="{}">Cancel action</a>').format(self._item_type_label, undo_url)
content_api.delete(item)
content_api.save(item, ActionDescription.DELETION)
tg.flash(msg, CST.STATUS_OK, no_escape=True)
tg.redirect(next_url)
except ValueError as e:
back_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
tmpl_context.folder_id,
tmpl_context.thread_id)
msg = _('{} not deleted: {}').format(self._item_type_label, str(e))
tg.flash(msg, CST.STATUS_ERROR)
tg.redirect(back_url)
示例9: put_delete_undo
def put_delete_undo(self, item_id):
require_current_user_is_owner(int(item_id))
item_id = int(item_id)
content_api = ContentApi(tmpl_context.current_user, True, True) # Here we do not filter deleted items
item = content_api.get_one(item_id, self._item_type, tmpl_context.workspace)
try:
next_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
tmpl_context.folder_id,
tmpl_context.thread_id)
msg = _('{} undeleted.').format(self._item_type_label)
content_api.undelete(item)
content_api.save(item, ActionDescription.UNDELETION)
tg.flash(msg, CST.STATUS_OK)
tg.redirect(next_url)
except ValueError as e:
logger.debug(self, 'Exception: {}'.format(e.__str__))
back_url = tg.url('/workspaces/{}/folders/{}/threads/{}').format(tmpl_context.workspace_id,
tmpl_context.folder_id,
tmpl_context.thread_id)
msg = _('{} not un-deleted: {}').format(self._item_type_label, str(e))
tg.flash(msg, CST.STATUS_ERROR)
tg.redirect(back_url)
示例10: get_one
def get_one(self, idhost):
# pylint:disable-msg=C0111,R0201
host = get_host(idhost)
baseurl = tg.url("/api/v%s/hosts/%s" % (self.apiver, host.idhost))
result = {"id": host.idhost,
"name": host.name,
"href": baseurl,
"description": host.description,
"address": host.address,
"status": {
"name": host.state.name.statename,
"message": host.state.message,
"datetime": host.state.timestamp.isoformat(),
"order": host.state.name.order,
},
"tags": [t.name for t in host.tags],
}
result["lls"] = baseurl+"/lls/"
result["perfdatasources"] = baseurl+"/perfdatasources/"
result["graphs"] = baseurl+"/graphs/"
groups = []
for group in host.groups:
groups.append({
"id": group.idgroup,
"name": group.name,
"href": tg.url("/api/v%s/supitemgroups/%s"
% (self.apiver, group.idgroup)),
})
result["groups"] = groups
return dict(host=result)
示例11: post_login
def post_login( self, came_from = url( '/' ) ):
if not request.identity:
login_counter = request.environ['repoze.who.logins'] + 1
redirect( url( '/login', came_from = came_from, __logins = login_counter ) )
userid = request.identity['repoze.who.userid']
# flash('Welcome back, %s!' % userid)
redirect( came_from )
示例12: extern_create
def extern_create(self, *args, **kw):
'''
used to upload a file from another web application
kw must contain :
:file_path == file path
:description == verbose to explain some stuff
:project_name == name of the external web app
:sample_name == name of the plugin web app / or another thing
:sample_type == name of the webapp (and type of analysis if asked)
kw can contain :
:project_description == HTSstation project description
:task_id == task_id for BioScript files from HTSstation/BioScript
'''
#test if the essential kw are here
essential_kws = ["file_path", "description", "project_name", "sample_name", "sample_type"]
missing_kw = []
for k in essential_kws:
if k not in kw.keys():
missing_kw.append(k)
if len(missing_kw) > 0:
flash(str(missing_kw) + " not found in keywords. External application error.", "error")
raise redirect(url("/"))
session['backup_kw'] = kw
session.save()
#test if the user who was redirected on BioRepo is logged in it
if not 'repoze.who.identity' in request.environ:
session['extern_meas'] = True
session.save()
raise redirect(url('/login'))
else:
raise redirect(url('/measurements/external_add'))
示例13: submit
def submit(self, *args, **kwargs):
'''Create new submission for this assignment'''
if 'manage' not in request.permissions and \
request.user not in set(self.event.members) | set(self.event.tutorsandteachers):
abort(403)
if (not self.assignment.is_active and
not request.allowance(self.assignment)):
flash('This assignment is not active, you may not create a submission', 'warning')
redirect(url(self.assignment.url))
submission = Submission(
assignment=self.assignment,
filename=self.assignment.submission_filename or None,
source=self.assignment.submission_template or None,
language=self.assignment.allowed_languages[0] if self.assignment.allowed_languages else None,
user=request.user,
created=datetime.now(),
modified=datetime.now(),
)
DBSession.add(submission)
try:
DBSession.flush()
except SQLAlchemyError:
DBSession.rollback()
log.warn('Error creating new submission', exc_info=True)
flash('Error creating new submission', 'error')
redirect(url(self.assignment.url))
else:
redirect(url(submission.url + '/edit'))
示例14: events
def events(self, *args, **kw):
"""Handle the events page."""
e = model.events.Events()
event_list = e.getAll()
geojson = e.getAllGeoJson()
#geojson_l = e.getLastGeoJson()
#json_l = e.getLastJson()
b = model.bsb.BoletimSismico()
bsb_list = b.getAll()
geojson_l = b.getLastGeoJson()
f = ef.EventFilterForm().req()
bsb_f = bf.BsbFilterForm().req()
return dict(page='events',
filterForm = f,
bsbFilterForm = bsb_f,
events = event_list,
bsb = bsb_list,
cycle = cycle,
geojson = geojson,
geojson_l = geojson_l,
evt_png = url("/images/event.png"),
last_evt_png = url("/images/star2.png"),
)
示例15: reset_pwd
def reset_pwd(self, **kw):
u = DBSession.query(User).filter_by(email_address=kw['e'])\
.filter_by(verify_code=kw['vc'])\
.first()
if not u:
flash(_('Invalid email address or verification code!'), 'warn')
redirect(url('/'))
new_pass = _h.gen_password()
u.password = new_pass
# the email
msg = turbomail.Message(
"[email protected]",
u.email_address,
"Neighbor Farms Password Reset"
)
msg.plain = PASSWORD_RESET_MSG % (u.display_name, u.email_address, new_pass, config['base_url'])
DBSession.flush()
transaction.commit()
msg.send()
flash(_("You're password has been reset, and sent via email."), 'info')
redirect(url('/login'))