Python werkzeug.exceptions.BadRequest() Examples

The following are 30 code examples of werkzeug.exceptions.BadRequest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module werkzeug.exceptions , or try the search function .
Example #1
Source File: test_http.py    From bepasty-server with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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') 
Example #2
Source File: wrappers.py    From Financial-Portfolio-Flask with MIT License 6 votes vote down vote up
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() 
Example #3
Source File: server.py    From octavia with Apache License 2.0 6 votes vote down vote up
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')) 
Example #4
Source File: wrappers.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
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() 
Example #5
Source File: wrappers.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: wrappers.py    From lambda-packs with MIT License 6 votes vote down vote up
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 #7
Source File: wrappers.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: rest_service.py    From scrapy-cluster with MIT License 6 votes vote down vote up
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 
Example #9
Source File: profile.py    From listenbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def reset_latest_import_timestamp():
    if request.method == "POST":
        token = request.form.get("token")
        if token != current_user.auth_token:
            raise BadRequest("Can only reset latest import timestamp of currently logged in user")
        reset = request.form.get("reset")
        if reset == "yes":
            try:
                db_user.reset_latest_import(current_user.musicbrainz_id)
                flash.info("Latest import time reset, we'll now import all your data instead of stopping at your last imported listen.")
            except DatabaseException:
                flash.error("Something went wrong! Unable to reset latest import timestamp right now.")
        return redirect(url_for("profile.info"))
    else:
        token = current_user.auth_token
        return render_template(
            "profile/resetlatestimportts.html",
            token=token,
        ) 
Example #10
Source File: wrappers.py    From jbox with MIT License 6 votes vote down vote up
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 #11
Source File: api_compat_deprecated.py    From listenbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def submit_now_playing():
    """ Handle now playing notifications sent by clients """

    current_app.logger.info(json.dumps(request.form, indent=4))

    try:
        session = _get_session(request.form.get('s', ''))
    except BadRequest:
        return 'BADSESSION\n', 401

    listen = _to_native_api(request.form, append_key='')
    if listen is None:
        return 'FAILED Invalid data submitted!\n', 400


    listens = [listen]
    user = db_user.get(session.user_id)
    insert_payload(listens, user, LISTEN_TYPE_PLAYING_NOW)

    return 'OK\n' 
Example #12
Source File: wrappers.py    From jbox with MIT License 6 votes vote down vote up
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() 
Example #13
Source File: wrappers.py    From recruit with Apache License 2.0 6 votes vote down vote up
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() 
Example #14
Source File: wrappers.py    From Financial-Portfolio-Flask with MIT License 6 votes vote down vote up
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 #15
Source File: profile.py    From listenbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def reset_token():
    if request.method == "POST":
        token = request.form.get("token")
        if token != current_user.auth_token:
            raise BadRequest("Can only reset token of currently logged in user")
        reset = request.form.get("reset")
        if reset == "yes":
            try:
                db_user.update_token(current_user.id)
                flash.info("Access token reset")
            except DatabaseException:
                flash.error("Something went wrong! Unable to reset token right now.")
        return redirect(url_for("profile.info"))
    else:
        token = current_user.auth_token
        return render_template(
            "user/resettoken.html",
            token=token,
        ) 
Example #16
Source File: http.py    From bepasty-server with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #17
Source File: source.py    From spendb with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #18
Source File: views.py    From mbspotify with GNU General Public License v2.0 6 votes vote down vote up
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()],
    }) 
Example #19
Source File: test_usage.py    From flask-pundit with MIT License 6 votes vote down vote up
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) 
Example #20
Source File: test_usage.py    From flask-pundit with MIT License 6 votes vote down vote up
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) 
Example #21
Source File: controllers.py    From indico-plugins with MIT License 6 votes vote down vote up
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) 
Example #22
Source File: views.py    From mbspotify with GNU General Public License v2.0 6 votes vote down vote up
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 #23
Source File: wrappers.py    From scylla with Apache License 2.0 6 votes vote down vote up
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() 
Example #24
Source File: wrappers.py    From planespotter with MIT License 6 votes vote down vote up
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 #25
Source File: predict.py    From MAX-Audio-Embedding-Generator with Apache License 2.0 6 votes vote down vote up
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 
Example #26
Source File: wrappers.py    From planespotter with MIT License 6 votes vote down vote up
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() 
Example #27
Source File: wrappers.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
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() 
Example #28
Source File: wrappers.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
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() 
Example #29
Source File: wrappers.py    From Flask-P2P with MIT License 6 votes vote down vote up
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 #30
Source File: basic.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_trapping_of_bad_request_key_errors(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/fail')
        def fail():
            flask.request.form['missing_key']
        c = app.test_client()
        self.assert_equal(c.get('/fail').status_code, 400)

        app.config['TRAP_BAD_REQUEST_ERRORS'] = True
        c = app.test_client()
        try:
            c.get('/fail')
        except KeyError as e:
            self.assert_true(isinstance(e, BadRequest))
        else:
            self.fail('Expected exception')