本文整理汇总了Python中pylons.controllers.util.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了abort函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _vote_save
def _vote_save(self):
post = request.POST
# Fetch POST data
vote = post.get(u'vote')
email = post.get(u'email')
op = post.get(u'op')
attachment = post.get(u'vote-attachment')
comment = post.get(u'vote-comment')
fp = attachment.file if isinstance(attachment, cgi.FieldStorage) else None
attachment_data = fp.read(256).decode('utf-8') if fp else '<None>' # Note: assume plain text utf-8 file
#raise Exception('Inspect POST data')
# Validate request
if not (post.get(secure_form.token_key, None) == secure_form.authentication_token()):
abort (403, detail=u'Not permitted (possible CSRF attack)')
# Validate POST data: in practice we should not abort but rather redirect to the form
# with all the errors highlighted
vote = int(vote)
if not (vote >= 0 and vote <= 10):
abort (400, detail=u'Bad value for vote')
# Done with validation, now just log this and store the (vote,email) in the underlying model
log.info ('Saving vote for poll (%r)' %(dict(vote=vote, email=email, op=op, attachment_data=attachment_data)))
db_session = model.Session()
v = model.Vote (vote=vote, email=email, created_at=None, description=comment);
db_session.add(v)
db_session.commit()
# Done with form processing, redirect to a normal (GET) request ...
h.flash('Your vote is saved!')
redirect (url(controller='poll', action='results'))
return
开发者ID:drmalex07,项目名称:pylons-helloworld,代码行数:34,代码来源:poll.py
示例2: index
def index(self):
c.pins = []
try:
c.pins = Session.query(ModeratorPin).filter(ModeratorPin.username==session.get('username')).all()
except Exception, e:
log.critical('Could not get pins: %s' % e)
abort(500)
开发者ID:mehulsbhatt,项目名称:conference,代码行数:7,代码来源:conferences.py
示例3: run
def run(self, message_id):
if message_id:
try:
aid = int(message_id, 36)
return Message._byID(aid, True)
except (NotFound, ValueError):
abort(404, 'page not found')
开发者ID:cmak,项目名称:reddit,代码行数:7,代码来源:validator.py
示例4: index
def index(self, format='json'):
"""GET /: return all features."""
# If no filter argument is passed to the protocol index method
# then the default MapFish filter is used.
#
# If you need your own filter with application-specific params
# taken into acount, create your own filter and pass it to the
# protocol read method.
#
# E.g.
#
# from sqlalchemy.sql import and_
#
# default_filter = create_default_filter(request, BroadbandSpeed)
# filter = and_(default_filter, BroadbandSpeed.columname.ilike('%value%'))
# return self.protocol.read(request, filter=filter)
default_filter = create_default_filter(request, BroadbandSpeed)
if "zones_f" in request.params:
#zones will be a javascript list
zones_q = request.params["zones_f"].split(",")
#zones = Session.query(functions.geometry_type(functions.collect(Zone.geom))).filter(and_(Zone.zone_general.in_(zones_q),
# Zone.geom != None)).scalar()
zones = Session.query(functions.union(Zone.geom)).filter(Zone.zone_general.in_(zones_q)).first()
filter = and_(default_filter, BroadbandSpeed.geom.within(zones))
else:
filter = default_filter
if format != 'json':
abort(404)
return self.protocol.read(request, filter=filter)
开发者ID:gocodeboulder,项目名称:hotspots-mapfish,代码行数:31,代码来源:broadband_speeds.py
示例5: getrecord
def getrecord():
data = self.get_base_response(verb,body)
by_doc_ID = self._check_bool_param(params,'by_doc_ID')
by_resource_ID = self._check_bool_param(params,'by_resource_ID')
if not params.has_key(self.REQUESTID):
data['OK'] = False
data['error'] = 'badArgument'
return json.dumps(data)
if by_doc_ID and by_resource_ID:
data['OK'] = False
data['error'] = 'badArgument'
return json.dumps(data)
request_id = params[self.REQUESTID]
if by_doc_ID:
document = h.get_record(request_id)
if document is not None:
records = map(lambda doc: {"header":{'identifier':doc['_id'], 'datestamp':helpers.convertToISO8601Zformat(datetime.today()),'status':'active'},'resource_data':doc},[document])
else:
records = []
else:
records = map(lambda doc: {"header":{'identifier':doc['_id'], 'datestamp':helpers.convertToISO8601Zformat(datetime.today()),'status':'active'},'resource_data':doc},h.get_records_by_resource(request_id))
if len(records) == 0:
abort(500,'idDoesNotExist')
data['getrecord'] ={
'record': records
}
data['request']['identifier'] = request_id
data['request']['by_doc_ID'] = by_doc_ID
data['request']['by_resource_ID'] = by_resource_ID
return json.dumps(data)
开发者ID:andreyfedoseev,项目名称:LearningRegistry,代码行数:30,代码来源:harvest.py
示例6: check_session
def check_session():
'''
This function checks the session cookie for management API
and compares it to the session parameter
'''
if isSelfTest():
return
# check if the client is in the allowed IP range
no_session_clients = [c.strip() for c in config.get("linotpNoSessionCheck", "").split(",")]
client = request.environ.get('REMOTE_ADDR', None)
log.debug("[check_session] checking %s in %s" % (client, no_session_clients))
for network in no_session_clients:
if not network:
continue
try:
if IPAddress(client) in IPNetwork(network):
log.debug("[check_session] skipping session check since client %s in allowed: %s" % (client, no_session_clients))
return
except Exception as ex:
log.warning("[check_session] misconfiguration in linotpNoSessionCheck: %r - %r" % (network, ex))
if request.path.lower() == '/admin/getsession':
log.debug('[check_session] requesting a new session cookie')
else:
cookie = request.cookies.get('admin_session')
session = request.params.get('session')
# doing any other request, we need to check the session!
log.debug("[check_session]: session: %s" % session)
log.debug("[check_session]: cookie: %s" % cookie)
if session is None or session == "" or session != cookie:
log.error("[check_session] The request did not pass a valid session!")
abort(401, "You have no valid session!")
pass
开发者ID:richarddlmay,项目名称:Elm,代码行数:34,代码来源:util.py
示例7: evaluate
def evaluate(self, id=None):
if not h.auth.is_logged_in():
abort(401)
c.idea = h.fetch_obj(Idea, id, new_id=True)
node_q = Session.query(Node).filter_by(concept_id=id)
c.node = node_q.first()
if request.environ.get('REMOTE_USER', False):
user = h.get_user(request.environ['REMOTE_USER'])
sq = Session.query(IdeaEvaluation.cons_id)
sq = sq.filter(IdeaEvaluation.ante==c.idea)
sq = sq.filter(IdeaEvaluation.uid==user.ID)
sq = sq.subquery()
to_evaluate = c.idea.related.outerjoin((sq, Idea.ID==sq.c.cons_id))
to_evaluate = to_evaluate.filter(sq.c.cons_id==None)
else:
to_evaluate = c.idea.related
c.paginator = paginate.Page(
to_evaluate,
page=int(request.params.get('page', 1)),
items_per_page=10,
controller='idea',
action='edit',
id=id
)
return render('idea/idea-edit.html')
开发者ID:camerontt2000,项目名称:inphosite,代码行数:32,代码来源:idea.py
示例8: _location_action
def _location_action(self, path, obj_type=None):
location = LocationTag.get(path)
if location is None:
abort(404)
c.security_context = location
c.object_location = None
c.location = location
c.selected_sub_department_id = request.params.get('sub_department_id', None)
c.selected_sub_department = None
if c.selected_sub_department_id:
subdepartment = SubDepartment.get(c.selected_sub_department_id)
c.selected_sub_department = subdepartment
c.menu_items = subdepartment_menu_items(subdepartment)
else:
c.tabs = location_feed_subtabs(location)
if c.user:
c.menu_items = location_menu_items(location)
else:
c.menu_items = location_menu_public_items(location)
c.breadcrumbs = location_breadcrumbs(location)
c.theme = location.get_theme()
c.notabs = True
c.current_menu_item = None
if obj_type is None:
return method(self, location)
else:
return method(self, location, obj_type)
开发者ID:nous-consulting,项目名称:ututi,代码行数:34,代码来源:location.py
示例9: _subdepartmnet_action
def _subdepartmnet_action(self, path, subdept_id, obj_type=None):
location = LocationTag.get(path)
if location is None:
abort(404)
subdepartment = meta.Session.query(SubDepartment).filter_by(id=subdept_id).one()
if subdepartment is None:
abort(404)
c.security_context = location
c.object_location = None
c.location = location
c.breadcrumbs = subdepartment_breadcrumbs(subdepartment)
c.subdepartment = subdepartment
c.theme = location.get_theme()
c.notabs = True
c.menu_items = subdepartment_menu_items(subdepartment)
c.current_menu_item = None
if obj_type is None:
return method(self, location, subdepartment)
else:
return method(self, location, subdepartment, obj_type)
开发者ID:nous-consulting,项目名称:ututi,代码行数:25,代码来源:location.py
示例10: _reset
def _reset(self, username=None):
username = username or request.environ.get('REMOTE_USER', False)
if not username:
abort(401)
try:
user = h.get_user(username)
except:
abort(400)
new_password = user.reset_password()
msg = Message("[email protected]", user.email,
"InPhO password reset")
msg.plain = """
%(name)s, your password at the Indiana Philosophy Ontology (InPhO) has been changed to:
Username: %(uname)s
Password: %(passwd)s
The Indiana Philosophy Ontology (InPhO) Team
[email protected]
""" % {'passwd' : new_password,
'uname' : user.username,
'name' : user.fullname or user.username or ''}
msg.send()
Session.commit()
h.redirect(h.url(controller='account', action='reset_result'))
开发者ID:colinallen,项目名称:inphosite,代码行数:30,代码来源:account.py
示例11: submit_changes
def submit_changes(self):
'''
This function validates the submitted profile edit form and commits the
changes. Restricted to ``POST`` requests. If successful, redirects to
the result action to prevent resubmission.
'''
if not h.auth.is_logged_in():
abort(401)
c.user = h.get_user(request.environ['REMOTE_USER'])
if self.form_result['password'] != '':
c.user.set_password(self.form_result['password'])
# TODO: Enable area editing
#c.user.first_area_id=self.form_result['first_area'],
#user.first_area_level=self.form_result['first_area_level'],
#if self.form_result['second_area']:
# c.user.second_area_id=self.form_result['second_area'],
# c.user.second_area_level=self.form_result['second_area_level']
c.user.fullname = self.form_result['fullname']
Session.flush()
Session.commit()
h.redirect(h.url(controller='account', action='profile', message='edited'))
开发者ID:colinallen,项目名称:inphosite,代码行数:27,代码来源:account.py
示例12: enzyme_conc_edit
def enzyme_conc_edit(self, id=None):
if id is None:
abort(404)
conc = Session.query(EnzymeConcentration).get(id)
if not conc:
abort(404)
c.conc = conc
enzyme_field = fl.enzyme_field(selected=unicode(conc.enzyme_id))
assay_field = fl.assay_field(blank=True, selected=unicode(conc.assay.id))
author_field = fl.person_field(selected=unicode(conc.author_id))
c.plate = None
c.form = h.LiteralFormSelectPatch(
value={
"enzyme_id": enzyme_field["value"],
"assay_id": assay_field["value"],
"author_id": author_field["value"],
"minimum_conc": conc.minimum_conc,
"maximum_conc": conc.maximum_conc,
"source_plate_id": conc.source_plate_id,
"notes": conc.notes,
},
option={
"enzyme_id": enzyme_field["options"],
"assay_id": assay_field["options"],
"author_id": author_field["options"],
},
)
return render("/assay/enzyme/edit.html")
开发者ID:v-makarenko,项目名称:vtoolsmq,代码行数:31,代码来源:assay.py
示例13: save
def save(self, id=None):
"""
"""
if id is None:
abort(404)
assay_q = Session.query(Assay)
assay = assay_q.filter_by(id=id).first()
if assay is None:
abort(404)
reload_sequences = False
for k, v in self.form_result.items():
if k in ("primer_fwd", "primer_rev", "chromosome", "probe_pos", "amplicon_width", "snp_rsid"):
if getattr(assay, k) != v:
reload_sequences = True
if k not in ("id"):
setattr(assay, k, v)
# blow away previous sequences; on view, this will update.
if reload_sequences:
cached_sequences = assay.cached_sequences
for i in range(len(cached_sequences)):
cs = cached_sequences[-1]
snps = cs.snps
for j in range(len(snps)):
snp = snps.pop()
Session.delete(snp)
cached_sequences.pop()
Session.delete(cs)
self.__update_tms(assay)
Session.commit()
session.save()
redirect(url(controller="assay", action="view", id=assay.id))
开发者ID:v-makarenko,项目名称:vtoolsmq,代码行数:35,代码来源:assay.py
示例14: view
def view(self, dataset, dimension, format='html'):
self._get_dataset(dataset)
try:
c.dimension = c.dataset[dimension]
except KeyError:
abort(404, _('This is not a dimension'))
if not isinstance(c.dimension, model.Dimension):
abort(404, _('This is not a dimension'))
page = self._get_page('page')
cache = AggregationCache(c.dataset)
result = cache.aggregate(drilldowns=[dimension], page=page,
pagesize=PAGE_SIZE)
items = result.get('drilldown', [])
c.values = [(d.get(dimension), d.get('amount')) for d in items]
if format == 'json':
return to_jsonp({
"values": c.values,
"meta": c.dimension.as_dict()})
c.page = Page(c.values, page=page,
item_count=result['summary']['num_drilldowns'],
items_per_page=PAGE_SIZE,
presliced_list=True)
return render('dimension/view.html')
开发者ID:doismellburning,项目名称:openspending,代码行数:26,代码来源:dimension.py
示例15: index
def index(self, slave=None):
if 'numbuilds' in request.GET:
count = int(request.GET.getone('numbuilds'))
else:
count = 25
if 'format' in request.GET:
format = request.GET.getone('format')
else:
format = 'html'
if format not in ('html', 'json'):
abort(400, detail='Unsupported format: %s' % format)
# if slave is not None:
# slave = slave[0]
if 'slave' in request.GET:
slave = request.GET.getall('slave')
builds = GetHistoricBuilds(slave=slave, count=count)
# Return a rendered template
# or, return a json blob
if format == "html":
c.recent_builds = builds
return render("/recent.mako")
else:
for b in builds:
for k,v in b.items():
if isinstance(v, datetime.datetime):
v = times.UTC.localize(v)
b[k] = times.dt2ts(v)
return self.jsonify(builds)
开发者ID:hwine,项目名称:build-buildapi,代码行数:32,代码来源:recent.py
示例16: _search_teachers
def _search_teachers(self, location, text, sub_department_id=None):
locations = [loc.id for loc in location.flatten]
query = meta.Session.query(Teacher)\
.filter(Teacher.location_id.in_(locations))
if sub_department_id:
query = query.filter_by(sub_department_id=sub_department_id)
if text:
query = query.filter(Teacher.fullname.contains(text))
try:
page_no = int(request.params.get('page', 1))
except ValueError:
abort(404)
c.page = page_no
c.results = paginate.Page(
query,
page=c.page,
items_per_page=30,
item_count=search_query_count(query),
obj_type='teacher')
c.searched = True
开发者ID:nous-consulting,项目名称:ututi,代码行数:25,代码来源:location.py
示例17: rate
def rate(self, slug, up=None, down=None, **kwargs):
"""Say 'I like this' for the given media.
:param slug: The media :attr:`~mediadrop.model.media.Media.slug`
:rtype: unicode
:returns:
The new number of likes
"""
media = fetch_row(Media, slug=slug)
request.perm.assert_permission(u'view', media.resource)
if up:
if not request.settings['appearance_show_like']:
abort(status_code=403)
media.increment_likes()
elif down:
if not request.settings['appearance_show_dislike']:
abort(status_code=403)
media.increment_dislikes()
if request.is_xhr:
return u''
else:
redirect(action='view')
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:25,代码来源:media.py
示例18: catalog
def catalog(self, location, obj_type):
c.current_menu_item = obj_type + 's'
self.form_result['tagsitem'] = location.hierarchy()
self.form_result['obj_type'] = obj_type
c.text = self.form_result.get('text', '')
if obj_type == 'teacher':
self._search_teachers(location, c.text, c.selected_sub_department_id)
elif obj_type == 'department':
self._list_departments(location, c.text)
elif obj_type == 'sub_department':
self._list_sub_departments(location, c.text)
else:
self._search()
c.sub_departments = []
if obj_type == 'teacher':
c.sub_departments = [sub_department
for sub_department in c.location.sub_departments
if bool(sub_department.teachers)]
elif obj_type == 'subject':
c.sub_departments = [sub_department
for sub_department in c.location.sub_departments
if bool(sub_department.subjects)]
# render template by object type
if obj_type in self.catalog_template_names:
c.current_menu_item = obj_type
return render(self.catalog_template_names[obj_type])
else:
abort(404)
开发者ID:nous-consulting,项目名称:ututi,代码行数:33,代码来源:location.py
示例19: ratelimit_agent
def ratelimit_agent(agent):
key = 'rate_agent_' + agent
if g.cache.get(key):
request.environ['retry_after'] = 1
abort(429)
else:
g.cache.set(key, 't', time = 1)
开发者ID:blitz80690,项目名称:reddit,代码行数:7,代码来源:reddit_base.py
示例20: login
def login(self):
"login"
if request.remote_addr in session:
if session[request.remote_addr] > now():
abort(409, _('You have been banned after'
' several failed logins'))
else:
del session[request.remote_addr]
session.save()
identity = request.environ.get('repoze.who.identity')
came_from = unquote(str(request.GET.get('came_from', '')))
if not came_from or ' ' in came_from:
came_from = url('home')
if '://' in came_from:
from_url = urlparse(came_from)
came_from = from_url[2]
if identity:
redirect(url(came_from))
else:
c.came_from = came_from
c.login_counter = request.environ['repoze.who.logins']
if c.login_counter >= 3:
ban_until = now() + timedelta(minutes=5)
if request.remote_addr not in session:
session[request.remote_addr] = ban_until
session.save()
else:
if now() > session[request.remote_addr]:
del session[request.remote_addr]
session.save()
c.form = ResetPwForm(request.POST, csrf_context=session)
return render('/accounts/login.html')
开发者ID:TetraAsh,项目名称:baruwa2,代码行数:34,代码来源:accounts.py
注:本文中的pylons.controllers.util.abort函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论