Here are the examples of the python api werkzeug.exceptions.BadRequest taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
113 Examples
3
Example 1
Project: indico Source File: management.py
def _checkParams(self):
RHManageCategoryBase._checkParams(self)
target_category_id = request.form.get('target_category_id')
if target_category_id is None:
self.target_category = None
else:
self.target_category = Category.get_one(int(target_category_id), is_deleted=False)
if not self.target_category.can_manage(session.user):
raise Forbidden(_("You are not allowed to manage the selected destination."))
if self.target_category.events:
raise BadRequest(_("The destination already contains an event."))
3
Example 2
Project: mbspotify Source File: decorators.py
def key_required(func):
@wraps(func)
def wrapper(*args, **kwds):
if request.args.get('key') not in current_app.config['ACCESS_KEYS']:
raise BadRequest("You need to provide a key.")
return func(*args, **kwds)
return wrapper
3
Example 3
Project: flask-restful Source File: test_reqparse.py
def test_parse_foo_operators_four_hunderd(self):
app = Flask(__name__)
with app.app_context():
parser = RequestParser()
parser.add_argument("foo", type=int),
self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(Request.from_values("/bubble?foo=bar")))
3
Example 4
Project: lastuser Source File: resource.py
@lastuser_oauth.route('/api/1/avatar/edit', methods=['POST'])
@resource_registry.resource('avatar/edit', __(u"Update your profile picture"))
def resource_avatar_edit(authtoken, args, files=None):
"""
Set a user's avatar image
"""
avatar = args['avatar']
parsed = urlparse(avatar)
if parsed.scheme == 'https' and parsed.netloc:
# Accept any properly formatted URL.
# TODO: Add better validation.
authtoken.user.avatar = avatar
return {'avatar': authtoken.user.avatar}
else:
raise BadRequest(_("Invalid avatar URL"))
3
Example 5
Project: cgtd Source File: cgtd.py
def requires_authorization(f):
"""
Quick and dirty limit mutable api calls to only come from localhost.
REMIND: Sort authorization via api key etc....
"""
@wraps(f)
def decorated(*args, **kwargs):
if request.remote_addr != "127.0.0.1":
e = BadRequest("Authorization required")
raise e
return f(*args, **kwargs)
return decorated
3
Example 6
@cached_property
def parsed_data(self):
if self.parsed_content_type in self.environ.get('CONTENT_TYPE', ''):
try:
# TODO replace by own loads
return client.loads(self.decoded_data)
except Exception:
raise BadRequest('Unable to read XMl request')
else:
raise BadRequest('Not an XML request')
3
Example 7
Project: gae-angular-material-starter Source File: helpers.py
def make_bad_request_exception(message):
"""Raises 400 Bad request exception
Raises:
HTTPException: with 400 code
"""
raise exceptions.BadRequest(message)
3
Example 8
def on_json_loading_failed(self, e):
"""Called if decoding of the JSON data failed. The return value of
this method is used by :attr:`json` when an error ocurred.
"""
I_M_BAD = BadRequest()
I_M_BAD.json_parse_error = True
raise I_M_BAD
3
Example 9
Project: open-hackathon Source File: template_library.py
def __get_template_from_request(self):
""" get template dic from http post request
get file from request , then json load it to a dic
:return: template dic , if load file failed raise BadRequest exception
"""
for file_name in request.files:
try:
template = json.load(request.files[file_name])
self.log.debug("create template from file: %r" % template)
return template
except Exception as ex:
self.log.error(ex)
raise BadRequest(description="invalid template file")
3
Example 10
@cached_property
def json(self):
"""Get the result of simplejson.loads if possible."""
if 'json' not in self.environ.get('CONTENT_TYPE', ''):
raise BadRequest('Not a JSON request')
try:
return loads(self.data)
except Exception:
raise BadRequest('Unable to read JSON request')
3
Example 11
@staticmethod
def get_graphql_params(request, data):
query = request.args.get('query') or data.get('query')
variables = request.args.get('variables') or data.get('variables')
if variables and isinstance(variables, six.text_type):
try:
variables = json.loads(variables)
except:
raise HttpError(BadRequest('Variables are invalid JSON.'))
operation_name = request.args.get('operationName') or data.get('operationName')
return query, variables, operation_name
3
Example 12
Project: ggrc-core Source File: query.py
def init_query_view(app):
# pylint: disable=unused-variable
@app.route('/query', methods=['POST'])
@login_required
def query_objects():
"""Advanced object collection queries view."""
try:
return get_objects_by_query()
except (NotImplementedError, BadQueryException) as exc:
raise BadRequest(exc.message)
3
Example 13
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
"""
raise BadRequest()
3
Example 14
Project: restfulgit Source File: routes.py
@porcelain.route('/repos/<repo_key>/compare/<old_branch_or_tag_or_sha>...<new_branch_or_tag_or_sha>.diff')
@corsify
def get_compare_diff(repo_key, old_branch_or_tag_or_sha, new_branch_or_tag_or_sha):
context = request.args.get('context', 3) # NOTE: The `context` parameter is a RestfulGit extension
try:
context = int(context)
except ValueError:
raise BadRequest("context was not a valid integer")
if context < 0:
raise BadRequest("context must not non negative")
repo = get_repo(repo_key)
old_commit = get_commit_for_refspec(repo, old_branch_or_tag_or_sha)
new_commit = get_commit_for_refspec(repo, new_branch_or_tag_or_sha)
diff = _get_diff(repo, new_commit, against=old_commit, context_lines=context)
return Response(diff.patch or '', mimetype=mime_types.DIFF)
3
Example 15
Project: appmetrics Source File: test_wsgi.py
def test_handle_metric_new_app_error(self):
wsgi.handle_metric_new(req(dict(type="gauge")), "test")
with assert_raises(werkzeug.exceptions.BadRequest) as exc:
wsgi.handle_metric_new(req(dict(type="gauge")), "test")
assert_equal(exc.exception.description, "can't create metric gauge('test'): Metric test already exists of type Gauge")
3
Example 16
Project: indico Source File: management.py
def _get_contribution_track_updates(self, track_id):
updates = {}
if track_id is None:
updates['track_id'] = None
else:
track = self._conf.getTrackById(str(track_id))
if not track:
raise BadRequest('Invalid track id')
if track_id != self.contrib.track_id:
updates['track_id'] = track_id
return updates
3
Example 17
Project: flask-restful Source File: test_api.py
Function: test_handle_error_does_not_swallow_exceptions
Function: test_handle_error_does_not_swallow_exceptions
def test_handle_error_does_not_swallow_exceptions(self):
app = Flask(__name__)
api = flask_restful.Api(app)
exception = BadRequest('x')
with app.test_request_context('/foo'):
resp = api.handle_error(exception)
self.assertEquals(resp.status_code, 400)
self.assertEquals(resp.get_data(), b'{"message": "x"}\n')
3
Example 18
Project: cydra Source File: __init__.py
@blueprint.route('/usersettings/remove_pubkey', methods=['POST'])
def remove_pubkey():
if cydra_user.is_guest:
raise InsufficientPermissions()
fingerprint = request.form.get('fingerprint', None)
if fingerprint is None:
raise BadRequest('Fingerprint missing')
store = ExtensionPoint(IPubkeyStore, component_manager=cydra_instance)
store.remove_pubkey(cydra_user, fingerprint=fingerprint)
return redirect(url_for('.usersettings'))
3
Example 19
Project: appmetrics Source File: test_wsgi.py
def test_call_with_error_implicit(self):
self.handler.side_effect = werkzeug.exceptions.BadRequest()
body = self.mw(env("/_app-metrics/metrics", REQUEST_METHOD='GET'), self.start_response)
expected_body = json.dumps(werkzeug.exceptions.BadRequest.description)
assert_equal(b"".join(body), expected_body.encode('utf8'))
expected_headers = [
('Content-Type', 'application/json'),
('Content-Length', str(len(expected_body)))
]
assert_equal(
self.start_response.call_args_list,
[mock.call("400 BAD REQUEST", expected_headers)]
)
3
Example 20
Project: solace Source File: csrf.py
def exchange_token_protected(f):
"""Applies an exchange token check for each request to this view. Using
this also has the advantage that the URL generation system will
automatically put the exchange token into the URL.
"""
def new_view(request, *args, **kwargs):
if request.values.get('_xt') != get_exchange_token(request):
raise BadRequest()
return f(request, *args, **kwargs)
f.is_exchange_token_protected = True
return update_wrapper(new_view, f)
3
Example 21
def test_int_choice_types(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=int, choices=[1, 2, 3], location='json')
with app.test_request_context(
'/bubble', method='post',
data=json.dumps({'foo': 5}),
content_type='application/json'
):
try:
parser.parse_args()
self.fail()
except exceptions.BadRequest:
pass
3
Example 22
def test_int_range_choice_types(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=int, choices=range(100), location='json')
with app.test_request_context(
'/bubble', method='post',
data=json.dumps({'foo': 101}),
content_type='application/json'
):
try:
parser.parse_args()
self.fail()
except exceptions.BadRequest:
pass
3
Example 23
Project: appmetrics Source File: test_wsgi.py
def test_call_with_error_explicit(self):
self.handler.side_effect = werkzeug.exceptions.BadRequest(description="bad request received")
body = self.mw(env("/_app-metrics/metrics", REQUEST_METHOD='GET'), self.start_response)
expected_body = json.dumps("bad request received")
assert_equal(b"".join(body), expected_body.encode('utf8'))
expected_headers = [
('Content-Type', 'application/json'),
('Content-Length', str(len(expected_body)))
]
assert_equal(
self.start_response.call_args_list,
[mock.call("400 BAD REQUEST", expected_headers)]
)
3
Example 24
def on_exhausted(self):
"""This is called when the stream tries to read past the limit.
The return value of this function is returned from the reading
function.
Per default this raises a :exc:`~werkzeug.exceptions.BadRequest`.
"""
if self.silent:
return ''
from werkzeug.exceptions import BadRequest
raise BadRequest('input stream exhausted')
3
Example 25
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
3
Example 26
Project: ggrc-core Source File: converters.py
def handle_import_request():
try:
dry_run, csv_data = parse_import_request()
converter = Converter(dry_run=dry_run, csv_data=csv_data)
converter.import_csv()
response_data = converter.get_info()
response_json = json.dumps(response_data)
headers = [("Content-Type", "application/json")]
return current_app.make_response((response_json, 200, headers))
except: # pylint: disable=bare-except
logger.exception("Import failed")
raise BadRequest("Import failed due to server error.")
3
Example 27
Project: ggrc-core Source File: converters.py
def check_required_headers(required_headers):
errors = []
for header, valid_values in required_headers.items():
if header not in request.headers:
errors.append("Missing required header '{}'".format(header))
elif request.headers[header] not in valid_values:
errors.append("Invalid header value for '{}'".format(header))
if errors:
raise BadRequest("\n".join(errors))
3
Example 28
Project: DockCI Source File: test_user_api_db.py
@pytest.mark.usefixtures('db')
def test_add_fake(self):
""" Add a fake role to a user causes 400 and error message """
user = User()
with pytest.raises(werkzeug.exceptions.BadRequest) as excinfo:
rest_set_roles(user, ['testfake', 'testmore'])
assert 'testfake' in excinfo.value.data['message']['roles']
assert 'testmore' in excinfo.value.data['message']['roles']
3
Example 29
Project: nova-billing Source File: rest.py
def check_and_get_datatime(rj):
ret = utils.str_to_datetime(rj.get("datetime", None))
if not ret:
raise BadRequest(
description="valid datetime must be specified")
return ret
3
Example 30
Project: appmetrics Source File: test_wsgi.py
@raises(werkzeug.exceptions.BadRequest)
def test_handle_tag_add_invalid(self):
res = wsgi.handle_tag_add(mock.Mock(), "tag1", "test1")
assert_equal(res, "")
assert_equal(metrics.TAGS, {"tag1": {"test1"}})
3
Example 31
def get_blame(repo, file_path, newest_commit, oldest_refspec=None, min_line=1, max_line=None): # pylint: disable=R0913
kwargs = {
'flags': (GIT_BLAME_TRACK_COPIES_SAME_COMMIT_MOVES | GIT_BLAME_TRACK_COPIES_SAME_COMMIT_COPIES),
'newest_commit': newest_commit.id,
}
if oldest_refspec is not None:
oldest_commit = get_commit_for_refspec(repo, oldest_refspec)
kwargs['oldest_commit'] = oldest_commit.id
if min_line > 1:
kwargs['min_line'] = min_line
if max_line is not None:
kwargs['max_line'] = max_line
try:
return repo.blame(file_path, **kwargs)
except KeyError as no_such_file_err: # pragma: no cover
raise NotFound(no_such_file_err.message)
except ValueError: # pragma: no cover
raise BadRequest("path resolved to non-blob object")
3
Example 32
@cached_property
def parsed_data(self):
if self.parsed_content_type in self.environ.get('CONTENT_TYPE', ''):
try:
return json.loads(
self.decoded_data.decode(
self.charset, self.encoding_errors),
object_hook=JSONDecoder())
except Exception:
raise BadRequest('Unable to read JSON request')
else:
raise BadRequest('Not a JSON request')
3
Example 33
Project: indico Source File: controllers.py
def _process(self):
if session['login_identity'] == self.identity.id:
raise BadRequest("The identity used to log in can't be removed")
if self.user.local_identity == self.identity:
raise BadRequest("The main local identity can't be removed")
self.user.identities.remove(self.identity)
provider_title = multipass.identity_providers[self.identity.provider].title
flash(_("{provider} ({identifier}) successfully removed from your accounts"
.format(provider=provider_title, identifier=self.identity.identifier)), 'success')
return redirect(url_for('.accounts'))
3
Example 34
def get_json(self):
try:
data = json.loads(self.get_data(as_text=True))
except ValueError:
raise BadRequest(WEAVE_MALFORMED_JSON)
else:
if not isinstance(data, (dict, list)):
raise BadRequest(WEAVE_INVALID_WBO)
return data
3
Example 35
Project: indico Source File: management.py
def _get_contribution_session_updates(self, session_id):
updates = {}
if session_id is None:
updates['session'] = None
else:
session = Session.query.with_parent(self.event_new).filter_by(id=session_id).first()
if not session:
raise BadRequest('Invalid session id')
if session != self.contrib.session:
updates['session'] = session
return updates
3
Example 36
Project: cgstudiomap Source File: main.py
@http.route('/auth_openid/login/verify_direct', type='http', auth='none')
def verify_direct(self, db, url):
result = self._verify(db, url)
if 'error' in result:
return werkzeug.exceptions.BadRequest(result['error'])
if result['action'] == 'redirect':
return werkzeug.utils.redirect(result['value'])
return result['value']
3
Example 37
def put(self, obj_id=None):
"""update an object, new attrs should be passed in the payload"""
args = self.reqparse_args(right='write', default=False)
if not args:
raise BadRequest()
return self.controller.update({'id': obj_id}, args), 200
3
Example 38
Project: appmetrics Source File: test_wsgi.py
def test_handle_metric_new_generic_error(self):
new_gauge = mock.Mock(side_effect=ValueError("an error"))
with mock.patch.dict('appmetrics.wsgi.metrics.METRIC_TYPES', gauge=new_gauge):
with assert_raises(werkzeug.exceptions.BadRequest) as exc:
wsgi.handle_metric_new(req(dict(type="gauge")), "test")
assert_equal(exc.exception.description, "can't create metric gauge('test')")
3
Example 39
Project: gmusicprocurator Source File: proxy.py
@app.route('/search', methods=['POST'])
@online_only
def search():
"""
Search All Access for artists/albums/tracks.
Requires a JSON payload with one key: ``query``.
Returns the JSON results directly from the API.
"""
json = request.get_json()
if json is None:
return BadRequest('JSON payload required')
return jsonify(music.search(json['query']))
3
Example 40
Project: flask-restful Source File: test_api.py
Function: test_exception_header_forwarding_doesnt_duplicate_headers
Function: test_exception_header_forwarding_doesnt_duplicate_headers
def test_exception_header_forwarding_doesnt_duplicate_headers(self):
"""Test that HTTPException's headers do not add a duplicate
Content-Length header
https://github.com/flask-restful/flask-restful/issues/534
"""
app = Flask(__name__)
api = flask_restful.Api(app)
with app.test_request_context('/'):
r = api.handle_error(BadRequest())
self.assertEqual(len(r.headers.getlist('Content-Length')), 1)
3
Example 41
Project: acousticbrainz-server Source File: datasets.py
def _parse_dataset_csv(file):
classes_dict = defaultdict(list)
for class_row in csv.reader(file):
if len(class_row) != 2:
raise BadRequest("Bad dataset! Each row must contain one <MBID, class name> pair.")
classes_dict[class_row[1]].append(class_row[0])
classes = []
for name, recordings in six.iteritems(classes_dict):
classes.append({
"name": name,
"recordings": recordings,
})
return classes
3
Example 42
Project: isso Source File: comments.py
def preview(self, environment, request):
data = request.get_json()
if "text" not in data or data["text"] is None:
raise BadRequest("no text given")
return JSON({'text': self.isso.render(data["text"])}, 200)
3
Example 43
Project: mbspotify Source File: views.py
@main_bp.route("/mapping-jsonp/<mbid>")
@jsonp
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]})
3
Example 44
def test_type_callable_none(self):
app = Flask(__name__)
parser = RequestParser()
parser.add_argument("foo", type=lambda x: x, location="json", required=False),
with app.test_request_context('/bubble', method="post",
data=json.dumps({"foo": None}),
content_type='application/json'):
try:
args = parser.parse_args()
self.assertEquals(args['foo'], None)
except exceptions.BadRequest:
self.fail()
3
Example 45
def _forbidden_attributes(self, data):
for key in data.keys():
if key in self.reserved_keys:
if key == 'published':
raise Forbidden('You cannot publish a project via the API')
raise BadRequest("Reserved keys in payload")
3
Example 46
Project: isso Source File: comments.py
def counts(self, environ, request):
data = request.get_json()
if not isinstance(data, list) and not all(isinstance(x, str) for x in data):
raise BadRequest("JSON must be a list of URLs")
return JSON(self.comments.count(*data), 200)
3
Example 47
def __call__(self, func):
def dec(cls, env, req, *args, **kwargs):
if self.param not in req.args:
raise BadRequest("missing %s query" % self.param)
try:
kwargs[self.param] = self.type(req.args[self.param])
except TypeError:
raise BadRequest("invalid type for %s, expected %s" % (self.param, self.type))
return func(cls, env, req, *args, **kwargs)
return dec
3
Example 48
Project: appmetrics Source File: test_wsgi.py
def test_call_with_invalid_method(self):
self.handler.side_effect = werkzeug.exceptions.BadRequest()
body = self.mw(env("/_app-metrics/metrics", REQUEST_METHOD='POST'), self.start_response)
expected_body = json.dumps(werkzeug.exceptions.MethodNotAllowed.description)
assert_equal(b"".join(body), expected_body.encode('utf8'))
assert_equal(
self.start_response.call_args_list,
[mock.call("405 METHOD NOT ALLOWED", mock.ANY)]
)
headers = dict(self.start_response.call_args_list[0][0][1])
assert_equal(headers['Content-Type'], "application/json")
assert_equal(headers['Content-Length'], str(len(expected_body)))
allow = {x.strip() for x in headers['Allow'].split(",")}
assert_equal(allow, {"HEAD", "GET"})
3
Example 49
def on_exhausted(self):
"""This is called when the stream tries to read past the limit.
The return value of this function is returned from the reading
function.
"""
if self.silent:
return ''
from werkzeug.exceptions import BadRequest
raise BadRequest('input stream exhausted')
3
Example 50
Project: ggrc-core Source File: converters.py
def check_import_file():
if "file" not in request.files or not request.files["file"]:
raise BadRequest("Missing csv file")
csv_file = request.files["file"]
if not csv_file.filename.lower().endswith(".csv"):
raise BadRequest("Invalid file type.")
return csv_file