本文整理汇总了Python中werkzeug.exceptions.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了abort函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_quiz_view
def get_quiz_view(quiz_id):
try:
QuizProfile.get_by_composite_id(quiz_id,session['email'])
abort(401)
except NoSuchQuizProfileExistException as e:
quiz = Quiz.get_by_id(quiz_id)
return render_template('quiz/user/quiz.html', active_quiz=quiz.to_json())
开发者ID:jslvtr,项目名称:AC41004-Team-2,代码行数:7,代码来源:app.py
示例2: get_post
def get_post(id, check_author=True):
"""Get a post and its author by id.
Checks that the id exists and optionally that the current user is
the author.
:param id: id of post to get
:param check_author: require the current user to be the author
:return: the post with author information
:raise 404: if a post with the given id doesn't exist
:raise 403: if the current user isn't the author
"""
post = get_db().execute(
'SELECT p.id, title, body, created, author_id, username'
' FROM post p JOIN user u ON p.author_id = u.id'
' WHERE p.id = ?',
(id,)
).fetchone()
if post is None:
abort(404, "Post id {0} doesn't exist.".format(id))
if check_author and post['author_id'] != g.user['id']:
abort(403)
return post
开发者ID:AEliu,项目名称:flask,代码行数:26,代码来源:blog.py
示例3: test_proxy_exception
def test_proxy_exception():
orig_resp = Response('Hello World')
with pytest.raises(exceptions.HTTPException) as excinfo:
exceptions.abort(orig_resp)
resp = excinfo.value.get_response({})
assert resp is orig_resp
assert resp.get_data() == b'Hello World'
开发者ID:2009bpy,项目名称:werkzeug,代码行数:7,代码来源:test_exceptions.py
示例4: paginate
def paginate(self, page, per_page=20, error_out=True, sql=None):
"""Returns `per_page` items from page `page`. By default it will
abort with 404 if no items were found and the page was larger than
1. This behavor can be disabled by setting `error_out` to `False`.
Returns an :class:`Pagination` object.
"""
sql = sql.lower()
countsql = 'select count(*) as count from ({0}) tmp_count '.format(sql) #+ sql[sql.find('from'):]
#print(countsql)
if 'limit' in sql:
print("please del your limit keywords")
sql = sql + ' limit {0},{1}'.format((page - 1) * per_page, per_page)
#print(sql)
items =self.db().query(sql)
if error_out and page < 1:
abort(404)
# No need to count if we're on the first page and there are fewer
# items than we expected.
if page == 1 and len(items) < per_page:
total = len(items)
else:
#total = self.order_by(None).count()
total = self.db().get(countsql).count
return Pagination(self, page, per_page, total, items)
开发者ID:zihuxinyu,项目名称:mbp,代码行数:28,代码来源:DBLogic.py
示例5: _initialize
def _initialize(self, request, *args):
self._change_instance(request)
app_instance = '%s.instance' % conf('config.app')
if self.instance:
request.session[app_instance] = self.instance
instance_name = self.instance
else:
instance_name = request.args.get('instance', None)
if not instance_name:
instance_name = request.session.get(app_instance, None)
if instance_name:
request.session[app_instance] = instance_name
else:
abort(Response(
self._instance_selection(request),
mimetype='text/html')
)
self.instance_name = instance_name
self.instance_config = conf('crud.instances.%s.%s' % (
conf('config.app'),
self.instance_name
))
self._get_database()
self._get_session()
开发者ID:PabloRosales,项目名称:im-core-python,代码行数:27,代码来源:__init__.py
示例6: serve_slowly
def serve_slowly(path):
def octoberfest():
for bb in range(99, 2, -1):
yield ("0" * 65535) + "\n" # ENOUGH TO FILL THE INCOMING BUFFER
Thread.sleep(1.0 / RATE)
yield CNV.unicode2utf8(
expand_template(
"{{num}} bottles of beer on the wall! {{num}} bottles of beer! Take one down, pass it around! {{less}} bottles of beer on he wall!\n",
{"num": bb, "less": bb - 1},
)
)
yield ("0" * 65535) + "\n" # ENOUGH TO FILL THE INCOMING BUFFER
yield CNV.unicode2utf8(
u"2 bottles of beer on the wall! 2 bottles of beer! Take one down, pass it around! 1 bottle of beer on he wall!\n"
)
yield ("0" * 65535) + "\n" # ENOUGH TO FILL THE INCOMING BUFFER
yield CNV.unicode2utf8(
u"1 bottle of beer on the wall! 1 bottle of beer! Take one down, pass it around! 0 bottles of beer on he wall.\n"
)
try:
## FORWARD RESPONSE
return Response(octoberfest(), direct_passthrough=True, status=200) # FOR STREAMING
except Exception, e:
abort(400)
开发者ID:klahnakoski,项目名称:esFrontLine,代码行数:25,代码来源:test_slow_server.py
示例7: delete
def delete(id):
"""
删除 entry
返回 json
"""
int_value_verify(id)
old_entry = EntryService.get_by_id(id)
if not old_entry:
return jsonify(success=False,
redirect_url='/',
data_id=id)
# 防止删除别人的帖子
if old_entry.author_id != g.user.id and not g.user.is_supervisor:
abort(403)
next = request.args.get('next', None)
if next is None:
next = url_for('portal.category', category=old_entry.category.slug)
flash(_("The %(name)s has been deleted", name = old_entry.title), "success")
return jsonify(success=EntryService.delete(old_entry),
redirect_url=next,
data_id=id)
开发者ID:liushaochan,项目名称:cn486,代码行数:27,代码来源:entry.py
示例8: load
def load(client_id):
client_data = db.get(client_id)
if client_data:
return Tenant.from_map(client_data)
else:
_log.warn("Cannot find client: %s" % client_id)
abort(400)
开发者ID:chrishylen-wf,项目名称:ac-flask-hipchat,代码行数:7,代码来源:tenant.py
示例9: last_id
def last_id():
c = get_db().execute(
"SELECT max(id) from post"
)
if c == None:
abort(404, "No Posts exist")
return str(c.fetchone()[0])
开发者ID:ruanpienaar,项目名称:python,代码行数:7,代码来源:blog.py
示例10: add_recipe
def add_recipe():
if not session.get('logged_in'):
abort(401)
db.add_recipe(g.db, Recipe(request.form['title'], request.form['text']))
flash('New entry was successfully added')
return redirect(url_for('list_recipes'))
开发者ID:hanbei,项目名称:carl,代码行数:7,代码来源:views.py
示例11: update_recipe
def update_recipe(id):
if not session.get('logged_in'):
abort(401)
recipe = Recipe(request.form['title'], request.form['description'], id)
db.update_recipe(g.db, recipe)
return redirect(url_for('list_recipes'))
开发者ID:hanbei,项目名称:carl,代码行数:7,代码来源:views.py
示例12: load_from_web
def load_from_web(self, form, files):
try:
self.department = Department()
self.enterprise = Enterprise()
self.role = Role()
self.name = form['name']
self.department.load(int(form['departament']))
self.enterprise.load(int(form['enterprise']))
self.role.load(int(form['role']))
self.registry = load_int(form['registry'])
self.name_tag = load_int(form['name_tag'])
self.active = form['active'] == 'Y'
self.cpf = load_int(form['cpf'])
self.sex = nwe(form['sex'])
self.rg = nwe(form['rg'])
self.rg_issuing = nwe(form['rg_issuing'])
self.rg_date = nwe(form['rg_date'])
self.born_date = load_date(form['born_date'])
self.cnh = nwe(form['cnh'])
self.cnh_category = nwe(form['cnh_category'])
self.ctps = nwe(form['ctps'])
self.ctps_series = nwe(form['ctps_series'])
self.ctps_fu = nwe(form['ctps_fu'])
self.ctps_date = nwe(form['ctps_date'])
self.nacionality = nwe(form['nacionality'])
self.place_of_birth = nwe(form['place_of_birth'])
self.phone = load_int_as_str(form['phone'])
self.cellphone = load_int_as_str(form['cellphone'])
self.zipcode = load_int_as_str(form['zipcode'])
self.address = nwe(form['address'])
self.address_adjunct = nwe(form['address_adjunct'])
self.neighborhood = nwe(form['neighborhood'])
self.city = nwe(form['city'])
self.fu = nwe(form['fu'])
self.father_name = nwe(form['father_name'])
self.mother_name = nwe(form['mother_name'])
self.scholarity = load_int(form['scholarity'])
self.scholarity_complete = form['scholarity_complete'] == 'Y'
self.graduation = nwe(form['graduation'])
self.post_graduation = nwe(form['post_graduation'])
self.civil_state = nwe(form['civil_state'])
self.spouse = nwe(form['spouse'])
self.admission_date = load_date(form['admission_date'])
self.demission_date = load_date(form['demission_date'])
self.pis_date = load_date(form['pis_date'])
self.pis_number = load_int(form['pis_number'])
self.meal_on_enterprise = form['meal_on_enterprise'] == 'Y'
self.salary = load_decimal(form['salary'])
self.reservist = nwe(form['reservist'])
self.bank = nwe(form['bank'])
self.agency = nwe(form['agency'])
self.account = nwe(form['account'])
self.winthor_registry = load_int(form['winthor_registry'])
self.transport_voucher = form['transport_voucher'] == 'Y'
data = files['photo'].stream.read()
if data != b'':
self.photo = data
except BadRequestKeyError:
abort(403)
开发者ID:C-Element,项目名称:SigeLib,代码行数:60,代码来源:models.py
示例13: __init__
def __init__(self, row):
if not row:
logger.log('error', 'model', 'invalid id')
abort(418)
self.id = row.id
self.nodes = dict()
if hasattr(row, 'nodes') and row.nodes:
for node in row.nodes:
self.nodes[g.nodes[node['f1']]] = node['f2'] # f1 = node id, f2 = value
self.name = row.name
self.root = None
self.description = row.description if row.description else ''
self.system_type = row.system_type
self.created = row.created
self.modified = row.modified
self.first = int(row.first) if hasattr(row, 'first') and row.first else None
self.last = int(row.last) if hasattr(row, 'last') and row.last else None
self.class_ = g.classes[row.class_code]
self.dates = {}
self.view_name = None # view_name is used to build urls
if self.system_type == 'file':
self.view_name = 'file'
elif self.class_.code in app.config['CODE_CLASS']:
self.view_name = app.config['CODE_CLASS'][self.class_.code]
self.table_name = self.view_name # table_name is used to build tables
if self.view_name == 'place':
self.table_name = self.system_type.replace(' ', '-')
开发者ID:DigitisingPatternsOfPower,项目名称:OpenAtlas,代码行数:27,代码来源:entity.py
示例14: test_proxy_exception
def test_proxy_exception():
"""Proxy exceptions"""
orig_resp = Response('Hello World')
try:
abort(orig_resp)
except exceptions.HTTPException, e:
resp = e.get_response({})
开发者ID:EnTeQuAk,项目名称:werkzeug,代码行数:7,代码来源:test_exceptions.py
示例15: discount_codes_delete
def discount_codes_delete(discount_code_id=None):
discount_code = InvoicingManager.get_discount_code(discount_code_id)
if not discount_code:
abort(404)
delete_from_db(discount_code, "Discount code deleted")
flash("The discount code has been deleted.", "warning")
return redirect(url_for('.discount_codes_view'))
开发者ID:aviaryan,项目名称:open-event-orga-server,代码行数:7,代码来源:sales.py
示例16: get_geo
def get_geo():
"""
Get segments contained in database
"""
# Read JSON from request
json = request.get_json()
# Check bounding box in json request
if (json is None) or not ('start_lat' in json
and 'start_lon' in json
and 'end_lat' in json
and 'end_lon' in json):
abort(400, 'bounding box missing')
lat_min = min(json.get('start_lat'), json.get('end_lat'))
lat_max = max(json.get('start_lat'), json.get('end_lat'))
lon_min = min(json.get('start_lon'), json.get('end_lon'))
lon_max = max(json.get('start_lon'), json.get('end_lon'))
query = text('SELECT gid, osm_id, ST_AsText(ways.the_geom) '
'FROM ways '
'WHERE the_geom && ST_MakeEnvelope(:lon_min, :lat_min, :lon_max, :lat_max, 4326) '
'LIMIT 100;')
query_result = db.engine.execute(query, lon_min=lon_min, lat_min=lat_min, lon_max=lon_max, lat_max=lat_max)
segments = []
for row in query_result:
segments.append({
'gid': row[0],
'osm_id': row[1],
'coordinates': coordinates_from_linestring(row[2])
})
return jsonify({'segment_count': query_result.rowcount, 'segments': segments})
开发者ID:OpenCycleCompass,项目名称:ocyco-server-python,代码行数:29,代码来源:views.py
示例17: autor_livros_todos
def autor_livros_todos(params):
autor = Autores.collection().find_one({'_id': ObjectId(params.get('autor'))})
if autor:
autor = Autores.make_autor_from_dict(Autores(), autor)
return JSONEncoder().encode(autor.get_livros())
else:
abort(500)
开发者ID:alexandreferreira,项目名称:tata_library,代码行数:7,代码来源:autores_view.py
示例18: test_abort
def test_abort(code, name):
class_name = werkzeug_rfc7xx._msg_to_class_name(name)
class_obj = getattr(werkzeug_rfc7xx, class_name)
with pytest.raises(class_obj) as exc_info:
abort(code)
assert type(exc_info.value) is class_obj
开发者ID:onjin,项目名称:werkzeug-rfc7xx,代码行数:7,代码来源:test_rfc_7xx.py
示例19: get_knn_statics
def get_knn_statics():
if request.method != 'POST':
abort(403)
results = []
prefix_path = '/var/tmp/stylometric_app/knn_upload/'
f = request.files['file']
path = os.path.join(prefix_path, secure_filename(f.filename))
f.save(path)
if not os.path.exists(path):
abort(403)
qp = plaintext_data_etl.read_file_and_get_doc_list(path)
author_hash = dict([(row['author_id'], row['author_name']) for row in data_warehouse.get_all_author_id_and_name()])
try:
authors = session['authors']
feature_list, author_list = data_warehouse.get_features_from_database_fact_by_list_of_author_id(authors)
except KeyError:
feature_list, author_list = data_warehouse.get_all_features_from_database_fact()
knn_proba = cknn.get_query_set_probabilistic(feature_list, author_list, qp)
authors = list(set(author_list))
for idx in range(len(set(authors))):
results.append((author_hash.get(authors[idx]), knn_proba[idx]))
session.clear()
return jsonify(dict(results))
开发者ID:CityUHKDB,项目名称:pladetect_py,代码行数:32,代码来源:app.py
示例20: wsgi_app
def wsgi_app(self, environ, start_response):
"""This is the actual WSGI application. This is not implemented in
:meth:`__call__` so that middlewares can be applied without losing a
reference to the class. So instead of doing this::
app = MyMiddleware(app)
It's a better idea to do this instead::
app.wsgi_app = MyMiddleware(app.wsgi_app)
Then you still have the original application object around and
can continue to call methods on it.
This idea comes from `Flask`_.
:param environ:
A WSGI environment.
:param start_response:
A callable accepting a status code, a list of headers and an
optional exception context to start the response.
"""
cleanup = True
try:
request = self.request_class(environ)
if request.method not in self.allowed_methods:
abort(501)
match = self.router.match(request)
response = self.router.dispatch(request, match)
except Exception, e:
try:
response = self.handle_exception(request, e)
except HTTPException, e:
response = self.make_response(request, e)
开发者ID:peper,项目名称:tipfy,代码行数:35,代码来源:app.py
注:本文中的werkzeug.exceptions.abort函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论