werkzeug.exceptions.BadRequest

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 7

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."))

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

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")))

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"))

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

Example 6

Project: trytond Source File: xmlrpc.py
Function: parsed_data
    @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')

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)

Example 8

Project: pyjs Source File: requests.py
Function: on_json_loading_failed
    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

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")

Example 10

Project: ReproWeb Source File: wrappers.py
Function: json
    @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')

Example 11

Project: flask-graphql Source File: graphqlview.py
Function: get_graphql_params
    @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

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)

Example 13

Project: WAPT Source File: wrappers.py
Function: on_json_loading_failed
    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()

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)

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")

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

Example 17

Project: flask-restful Source File: test_api.py
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')

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'))

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)]
        )

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)

Example 21

Project: flask-restful Source File: test_reqparse.py
Function: test_int_choice_types
    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

Example 22

Project: flask-restful Source File: test_reqparse.py
Function: test_int_range_choice_types
    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

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)]
        )

Example 24

Project: flasktodo Source File: wsgi.py
Function: on_exhausted
    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')

Example 25

Project: ReproWeb Source File: wrappers.py
Function: parse_protobuf
    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

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.")

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))

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']

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

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"}})

Example 31

Project: restfulgit Source File: retrieval.py
Function: get_blame
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")

Example 32

Project: trytond Source File: jsonrpc.py
Function: parsed_data
    @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')

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'))

Example 34

Project: weave-minimal Source File: utils.py
Function: get_json
    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

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

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']

Example 37

Project: JARR Source File: common.py
Function: put
    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

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')")

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']))

Example 40

Project: flask-restful Source File: test_api.py
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)

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

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)

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]})

Example 44

Project: flask-restful Source File: test_reqparse.py
Function: test_type_callable_none
    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()

Example 45

Project: pybossa Source File: project.py
Function: forbidden_attributes
    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")

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)

Example 47

Project: isso Source File: __init__.py
Function: call
    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

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"})

Example 49

Project: ReproWeb Source File: wsgi.py
Function: on_exhausted
    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')

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
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3