本文整理汇总了Python中werkzeug.exceptions.BadRequest方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.BadRequest方法的具体用法?Python exceptions.BadRequest怎么用?Python exceptions.BadRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.exceptions
的用法示例。
在下文中一共展示了exceptions.BadRequest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_json_loading_failed
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def on_json_loading_failed(self, e):
"""Called if :meth:`get_json` parsing fails and isn't silenced. If
this method returns a value, it is used as the return value for
:meth:`get_json`. The default implementation raises a
:class:`BadRequest` exception.
.. versionchanged:: 0.10
Raise a :exc:`BadRequest` error instead of returning an error
message as JSON. If you want that behavior you can add it by
subclassing.
.. versionadded:: 0.8
"""
if current_app is not None and current_app.debug:
raise BadRequest('Failed to decode JSON object: {0}'.format(e))
raise BadRequest()
示例2: on_json_loading_failed
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def on_json_loading_failed(self, e):
"""Called if decoding of the JSON data failed. The return value of
this method is used by :meth:`get_json` when an error occurred. The
default implementation just raises a :class:`BadRequest` exception.
.. versionchanged:: 0.10
Removed buggy previous behavior of generating a random JSON
response. If you want that behavior back you can trivially
add it by subclassing.
.. versionadded:: 0.8
"""
ctx = _request_ctx_stack.top
if ctx is not None and ctx.app.config.get('DEBUG', False):
raise BadRequest('Failed to decode JSON object: {0}'.format(e))
raise BadRequest()
示例3: parse_protobuf
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def parse_protobuf(self, proto_type):
"""Parse the data into an instance of proto_type."""
if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''):
raise BadRequest('Not a Protobuf request')
obj = proto_type()
try:
obj.ParseFromString(self.data)
except Exception:
raise BadRequest("Unable to parse Protobuf request")
# Fail if not all required fields are set
if self.protobuf_check_initialization and not obj.IsInitialized():
raise BadRequest("Partial Protobuf request")
return obj
示例4: validate_json
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def validate_json(f):
"""Validate that the call is JSON."""
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
try:
if request.get_json() is None:
ret_dict = instance._create_ret_object(instance.FAILURE,
None, True,
instance.MUST_JSON)
instance.logger.error(instance.MUST_JSON)
return jsonify(ret_dict), 400
except BadRequest:
ret_dict = instance._create_ret_object(instance.FAILURE, None,
True,
instance.MUST_JSON)
instance.logger.error(instance.MUST_JSON)
return jsonify(ret_dict), 400
instance.logger.debug("JSON is valid")
return f(*args, **kw)
return wrapper
示例5: _decode_jwt_from_json
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def _decode_jwt_from_json(request_type):
if request.content_type != 'application/json':
raise NoAuthorizationError('Invalid content-type. Must be application/json.')
if request_type == 'access':
token_key = config.json_key
else:
token_key = config.refresh_json_key
try:
encoded_token = request.json.get(token_key, None)
if not encoded_token:
raise BadRequest()
except BadRequest:
raise NoAuthorizationError('Missing "{}" key in json data.'.format(token_key))
return encoded_token, None
示例6: plug_vip
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def plug_vip(self, vip):
# Catch any issues with the subnet info json
try:
net_info = flask.request.get_json()
assert type(net_info) is dict
assert 'subnet_cidr' in net_info
assert 'gateway' in net_info
assert 'mac_address' in net_info
except Exception:
raise exceptions.BadRequest(
description='Invalid subnet information')
return self._plug.plug_vip(vip,
net_info['subnet_cidr'],
net_info['gateway'],
net_info['mac_address'],
net_info.get('mtu'),
net_info.get('vrrp_ip'),
net_info.get('host_routes'))
示例7: parse
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def parse(cls, content_range):
"""
Parse Content-Range header.
Format is "bytes 0-524287/2000000".
"""
range_type, range_count = content_range.split(' ', 1)
# There are no other types then "bytes"
if range_type != 'bytes':
raise BadRequest
range_count, range_complete = range_count.split('/', 1)
range_begin, range_end = range_count.split('-', 1)
range_begin = int(range_begin)
range_end = int(range_end)
range_complete = int(range_complete)
if range_begin <= range_end < range_complete:
return ContentRange(range_begin, range_end, range_complete)
raise BadRequest
示例8: test_contentrange_parse
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def test_contentrange_parse():
r = ContentRange.parse('bytes 0-0/2')
assert r.begin == 0
assert r.end == 0
assert r.complete == 2
assert r.size == 1
assert not r.is_complete
r = ContentRange.parse('bytes 0-1/2')
assert r.begin == 0
assert r.end == 1
assert r.complete == 2
assert r.size == 2
assert r.is_complete
with pytest.raises(BadRequest):
ContentRange.parse('test 0-1/2')
with pytest.raises(BadRequest):
ContentRange.parse('bytes 1-0/2')
with pytest.raises(BadRequest):
ContentRange.parse('bytes 0-2/2')
示例9: test_verify_authorized_decorator_ignores_raised_exception
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def test_verify_authorized_decorator_ignores_raised_exception(self):
def do_authorize_stuff():
post = Post(1)
return self.pundit.authorize(post)
@self.app.route('/test_authorize_admin_get')
@verify_authorized
def admin_get_post():
g.user = {'id': 1, 'role': 'admin'}
raise BadRequest()
is_authorized = do_authorize_stuff()
if is_authorized:
return 'Success', 200
else:
return 'Forbidden', 403
resp = self.client.get('/test_authorize_admin_get')
eq_(resp.status_code, 400)
示例10: test_verify_either_decorator_success_with_authorize
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def test_verify_either_decorator_success_with_authorize(self):
def do_authorize_stuff():
post = Post(1)
return self.pundit.authorize(post)
@self.app.route('/test_authorize_admin_get')
@verify_authorized_or_policy_scoped
def admin_get_post():
g.user = {'id': 1, 'role': 'admin'}
raise BadRequest()
is_authorized = do_authorize_stuff()
if is_authorized:
return 'Success', 200
else:
return 'Forbidden', 403
resp = self.client.get('/test_authorize_admin_get')
eq_(resp.status_code, 400)
示例11: post
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def post(self):
"""Generate audio embedding from input data"""
result = {'status': 'error'}
args = input_parser.parse_args()
if not re.match("audio/.*wav", str(args['audio'].mimetype)):
e = BadRequest()
e.data = {'status': 'error', 'message': 'Invalid file type/extension'}
raise e
audio_data = args['audio'].read()
# Getting the predictions
preds = self.model_wrapper.predict(audio_data)
# Aligning the predictions to the required API format
result['embedding'] = preds.tolist()
result['status'] = 'ok'
return result
示例12: _process_POST
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def _process_POST(self):
original_url = self._make_absolute_url(request.args['original_url'])
shortcut = request.form['shortcut'].strip()
if not (set(shortcut) <= CUSTOM_SHORTCUT_ALPHABET):
raise BadRequest('Invalid shortcut')
result = register_shortcut(original_url, shortcut, session.user)
if result.get('error'):
kwargs = {'success': False, 'msg': self._get_error_msg(result)}
else:
kwargs = {'success': True, 'shorturl': result['short_url']}
return jsonify_template('ursh_custom_shortener_page.html', render_plugin_template,
event=self.event, ursh_host=self.ursh_host, shortcut=shortcut,
original_url=original_url, submitted=True, **kwargs)
示例13: sign
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def sign(dataset):
dataset = get_dataset(dataset)
require.dataset.update(dataset)
data = request_data()
if not data.get('file_name'):
raise BadRequest("You need to give a file name")
data['mime_type'] = data.get('mime_type') or 'application/octet-stream'
# create a stub:
source = extract_fileobj(dataset, fh=StringIO(),
file_name=data['file_name'],
mime_type=data['mime_type'])
# generate a policy document to replace with actual content:
res = generate_s3_upload_policy(source, data['file_name'],
data['mime_type'])
return jsonify(res)
示例14: mapping_spotify
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def mapping_spotify():
"""Endpoint for getting MusicBrainz entities mapped to a Spotify URI."""
uri = request.args.get("spotify_uri")
if uri is None:
raise BadRequest("`spotify_uri` argument is missing.")
if not uri.startswith("spotify:album:"):
raise BadRequest("Incorrect Spotify URI. Only albums are supported right now.")
conn = psycopg2.connect(**current_app.config["PG_INFO"])
cur = conn.cursor()
cur.execute("""
SELECT mbid::text
FROM mapping
WHERE is_deleted = FALSE AND spotify_uri = %s
""", (uri,))
return jsonify({
"mappings": [row[0] for row in cur.fetchall()],
})
示例15: mapping_jsonp
# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import BadRequest [as 别名]
def mapping_jsonp(mbid):
if not validate_uuid(mbid):
raise BadRequest("Incorrect MBID (UUID).")
conn = psycopg2.connect(**current_app.config["PG_INFO"])
cur = conn.cursor()
cur.execute("SELECT mbid, spotify_uri "
"FROM mapping "
"WHERE is_deleted = FALSE AND mbid = %s",
(mbid,))
if not cur.rowcount:
return jsonify({})
# TODO: Return all mappings to a specified MBID (don't forget to update userscript).
row = cur.fetchone()
return jsonify({mbid: row[1]})