Python werkzeug.exceptions.InternalServerError() Examples

The following are 29 code examples of werkzeug.exceptions.InternalServerError(). 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_index.py    From acousticbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def test_menu_logged_in_error_dont_show_no_user(self, mock_user_get):
        """ If the user is logged in, if we show a 500 error, do not show the user menu
            Don't query the database to get a current_user for the template context"""
        @self.app.route('/page_that_returns_500')
        def view500():
            raise InternalServerError('error')

        user = db_user.get_or_create('little_rsh')
        mock_user_get.return_value = user
        self.temporary_login(user['id'])
        resp = self.client.get('/page_that_returns_500')
        data = resp.data.decode('utf-8')
        # item not in user menu
        self.assertNotIn('Your profile', data)
        self.assertIn('Sign in', data)
        mock_user_get.assert_not_called()
        self.assertIsInstance(self.get_context_variable('current_user'), AnonymousUserMixin) 
Example #2
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_responds_with_validate(app, client):  # noqa
    import pytest
    from flask import jsonify
    from werkzeug.exceptions import InternalServerError

    class TestSchema(Schema):
        _id = fields.Integer(required=True)
        name = fields.String(required=True)

    @app.errorhandler(InternalServerError)
    def payload_validation_failure(err):
        return jsonify({"message": "Server attempted to return invalid data"}), 500

    @app.route("/test")
    @responds(schema=TestSchema, validate=True)
    def get():
        obj = {"wrong_field": 42, "name": "Jon Snow"}
        return obj

    with app.test_client() as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert resp.status_code == 500
        assert resp.json == {"message": "Server attempted to return invalid data"} 
Example #3
Source File: app.py    From annotated-py-projects with MIT License 6 votes vote down vote up
def handle_exception(self, e):
        """Default exception handling that kicks in when an exception
        occours that is not catched.  In debug mode the exception will
        be re-raised immediately, otherwise it is logged and the handler
        for a 500 internal server error is used.  If no such handler
        exists, a default 500 internal server error message is displayed.

        .. versionadded: 0.3
        """
        handler = self.error_handlers.get(500)
        if self.debug:
            raise
        self.logger.exception('Exception on %s [%s]' % (
            request.path,
            request.method
        ))
        if handler is None:
            return InternalServerError()
        return handler(e) 
Example #4
Source File: flask.py    From annotated-py-projects with MIT License 6 votes vote down vote up
def handle_exception(self, e):
        """Default exception handling that kicks in when an exception
        occours that is not catched.  In debug mode the exception will
        be re-raised immediately, otherwise it is logged and the handler
        for a 500 internal server error is used.  If no such handler
        exists, a default 500 internal server error message is displayed.

        .. versionadded: 0.3
        """
        handler = self.error_handlers.get(500)
        if self.debug:
            raise
        self.logger.exception('Exception on %s [%s]' % (
            request.path,
            request.method
        ))
        if handler is None:
            return InternalServerError()
        return handler(e) 
Example #5
Source File: test_index.py    From listenbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def test_menu_logged_in_error_dont_show_no_user(self, mock_user_get):
        """ If the user is logged in, if we show a 500 error, do not show the user menu
            Don't query the database to get a current_user for the template context"""
        @self.app.route('/page_that_returns_500')
        def view500():
            raise InternalServerError('error')

        user = db_user.get_or_create(1, 'iliekcomputers')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        user = db_user.get_or_create(1, 'iliekcomputers')
        mock_user_get.return_value = user
        self.temporary_login(user['login_id'])
        resp = self.client.get('/page_that_returns_500')
        data = resp.data.decode('utf-8')
        # item not in user menu
        self.assertNotIn('My Listens', data)
        self.assertNotIn('Sign in', data)
        self.assertIn('Import', data) 
Example #6
Source File: spotify_read_listens.py    From listenbrainz-server with GNU General Public License v2.0 6 votes vote down vote up
def submit_listens_to_listenbrainz(listenbrainz_user, listens, listen_type=LISTEN_TYPE_IMPORT):
    """ Submit a batch of listens to ListenBrainz

    Args:
        listenbrainz_user (dict): the user whose listens are to be submitted
        listens (list): a list of listens to be submitted
        listen_type: the type of listen (single, import, playing_now)
    """
    username = listenbrainz_user['musicbrainz_id']
    retries = 10
    while retries >= 0:
        try:
            current_app.logger.debug('Submitting %d listens for user %s', len(listens), username)
            insert_payload(listens, listenbrainz_user, listen_type=listen_type)
            current_app.logger.debug('Submitted!')
            break
        except (InternalServerError, ServiceUnavailable) as e:
            retries -= 1
            current_app.logger.error('ISE while trying to import listens for %s: %s', username, str(e))
            if retries == 0:
                raise spotify.SpotifyListenBrainzError('ISE while trying to import listens: %s', str(e)) 
Example #7
Source File: test_api_errors.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def test_api_error_unexpected_error_returns_json(self, mock_db_get):
        mock_db_get.side_effect = InternalServerError("Some bad thing happened")
        r = self.client.get('/1/stats/user/iliekcomputers/artists')
        self.assert500(r)
        self.assertEqual(r.json['error'], 'An unknown error occured.') 
Example #8
Source File: exceptions.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_aborter(self):
        abort = exceptions.abort
        self.assert_raises(exceptions.BadRequest, abort, 400)
        self.assert_raises(exceptions.Unauthorized, abort, 401)
        self.assert_raises(exceptions.Forbidden, abort, 403)
        self.assert_raises(exceptions.NotFound, abort, 404)
        self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD'])
        self.assert_raises(exceptions.NotAcceptable, abort, 406)
        self.assert_raises(exceptions.RequestTimeout, abort, 408)
        self.assert_raises(exceptions.Gone, abort, 410)
        self.assert_raises(exceptions.LengthRequired, abort, 411)
        self.assert_raises(exceptions.PreconditionFailed, abort, 412)
        self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413)
        self.assert_raises(exceptions.RequestURITooLarge, abort, 414)
        self.assert_raises(exceptions.UnsupportedMediaType, abort, 415)
        self.assert_raises(exceptions.UnprocessableEntity, abort, 422)
        self.assert_raises(exceptions.InternalServerError, abort, 500)
        self.assert_raises(exceptions.NotImplemented, abort, 501)
        self.assert_raises(exceptions.BadGateway, abort, 502)
        self.assert_raises(exceptions.ServiceUnavailable, abort, 503)

        myabort = exceptions.Aborter({1: exceptions.NotFound})
        self.assert_raises(LookupError, myabort, 404)
        self.assert_raises(exceptions.NotFound, myabort, 1)

        myabort = exceptions.Aborter(extra={1: exceptions.NotFound})
        self.assert_raises(exceptions.NotFound, myabort, 404)
        self.assert_raises(exceptions.NotFound, myabort, 1) 
Example #9
Source File: exceptions.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_aborter(self):
        abort = exceptions.abort
        self.assert_raises(exceptions.BadRequest, abort, 400)
        self.assert_raises(exceptions.Unauthorized, abort, 401)
        self.assert_raises(exceptions.Forbidden, abort, 403)
        self.assert_raises(exceptions.NotFound, abort, 404)
        self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD'])
        self.assert_raises(exceptions.NotAcceptable, abort, 406)
        self.assert_raises(exceptions.RequestTimeout, abort, 408)
        self.assert_raises(exceptions.Gone, abort, 410)
        self.assert_raises(exceptions.LengthRequired, abort, 411)
        self.assert_raises(exceptions.PreconditionFailed, abort, 412)
        self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413)
        self.assert_raises(exceptions.RequestURITooLarge, abort, 414)
        self.assert_raises(exceptions.UnsupportedMediaType, abort, 415)
        self.assert_raises(exceptions.UnprocessableEntity, abort, 422)
        self.assert_raises(exceptions.InternalServerError, abort, 500)
        self.assert_raises(exceptions.NotImplemented, abort, 501)
        self.assert_raises(exceptions.BadGateway, abort, 502)
        self.assert_raises(exceptions.ServiceUnavailable, abort, 503)

        myabort = exceptions.Aborter({1: exceptions.NotFound})
        self.assert_raises(LookupError, myabort, 404)
        self.assert_raises(exceptions.NotFound, myabort, 1)

        myabort = exceptions.Aborter(extra={1: exceptions.NotFound})
        self.assert_raises(exceptions.NotFound, myabort, 404)
        self.assert_raises(exceptions.NotFound, myabort, 1) 
Example #10
Source File: test_helpers.py    From kqueen with MIT License 5 votes vote down vote up
def test_get_object_malformed_user(self, bad_user):
        with pytest.raises(InternalServerError,
                           match='Missing namespace for class Cluster'):
            get_object(self.cluster.__class__, self.cluster.id, bad_user) 
Example #11
Source File: test_index.py    From acousticbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def test_menu_logged_in_error_dont_show_user_loaded(self, mock_user_get):
        """ If the user is logged in, if we show a 500 error, do not show the user menu
        If the user has previously been loaded in the view, check that it's not
        loaded while rendering the template"""

        user = db_user.get_or_create('little_rsh')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        user = db_user.get_or_create('little_rsh')
        mock_user_get.return_value = user

        @self.app.route('/page_that_returns_500')
        @login_required
        def view500():
            # flask-login user is loaded during @login_required, so check that the db has been queried
            mock_user_get.assert_called_with(user['id'])
            raise InternalServerError('error')

        self.temporary_login(user['id'])
        resp = self.client.get('/page_that_returns_500')
        data = resp.data.decode('utf-8')
        # item not in user menu
        self.assertNotIn('Your profile', data)
        self.assertIn('Sign in', data)
        # Even after rendering the template, the database has only been queried once (before the exception)
        mock_user_get.assert_called_once_with(user['id'])
        self.assertIsInstance(self.get_context_variable('current_user'), webserver.login.User) 
Example #12
Source File: test_dataset_eval.py    From acousticbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def test_get_job_details_internal_server_error(self, get_job):
        self.temporary_login(self.test_user_id)

        get_job.side_effect = InternalServerError()
        resp = self.client.get('/api/v1/datasets/evaluation/jobs/7804abe5-58be-4c9c-a787-22b91d031489', content_type='application/json')
        self.assertEqual(resp.status_code, 500)

        expected_result = {"message": "An unknown error occurred"}
        self.assertEqual(resp.json, expected_result) 
Example #13
Source File: test_datasets.py    From acousticbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def test_update_dataset_details_unknown_error(self, dataset_get):
        self.temporary_login(self.test_user_id)
        dsid = "e01f7638-3902-4bd4-afda-ac73d240a4b3"

        dataset_get.side_effect = InternalServerError()
        submit = {}
        url = "/api/v1/datasets/%s" % (dsid)
        resp = self.client.put(url, data=json.dumps(submit), content_type="application/json")

        self.assertEqual(resp.status_code, 500)
        expected_result = {"message": "An unknown error occurred"}
        self.assertEqual(resp.json, expected_result) 
Example #14
Source File: __init__.py    From TagBot with MIT License 5 votes vote down vote up
def error(e: InternalServerError) -> Union[HTML, JSON]:
    req_id = _request_id()
    # mypy really hates this.
    if request.is_json:
        json = {"error": "Internal server error", "request_id": req_id}
        return cast(JSON, (json, 500))
    html = render_template("500.html", request_id=req_id, tagbot_repo=TAGBOT_REPO_NAME)
    return html, 500 
Example #15
Source File: run.py    From sample-platform with ISC License 5 votes vote down vote up
def internal_error(error: InternalServerError):
    """Handle internal server error."""
    log.debug(f'500 error: {error}')
    log.debug('Stacktrace:')
    log.debug(traceback.format_exc())
    return 
Example #16
Source File: flask_server.py    From syntaxnet-api with Apache License 2.0 5 votes vote down vote up
def _parsey_universal_full_handler():
    text = request.get_data().decode('utf-8')
    language_code = request.headers.get('Content-Language', 'en').lower()
    try:
        conllu = parser[language_code].query(text, returnRaw=True)
        if conllu is None:
            raise InternalServerError('Bad SyntaxNet output')
        return app.response_class(conllu, mimetype='text/plain; charset=utf-8')
    except ValueError as e:
        raise BadRequest(e) 
Example #17
Source File: flask_app.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, import_name: str) -> None:
        shared_web_path = os.path.abspath(os.path.dirname(__file__))
        static_folder = os.path.join(shared_web_path, 'static')
        super().__init__(import_name, static_folder=static_folder)
        super().register_error_handler(DoesNotExistException, self.not_found)
        super().register_error_handler(exceptions.NotFound, self.not_found)
        super().register_error_handler(exceptions.InternalServerError, self.internal_server_error)
        super().route('/unauthorized/')(self.unauthorized)
        super().route('/logout/')(self.logout)
        super().route('/authenticate/')(self.authenticate)
        super().route('/authenticate/callback/')(self.authenticate_callback)
        super().route('/api/gitpull', methods=['POST'])(api.process_github_webhook)
        super().route('/api/commit')(api.commit_id)
        super().route('/robots.txt')(self.robots_txt)
        super().route('/favicon<rest>')(self.favicon)
        self.url_build_error_handlers.append(self.external_url_handler)
        if self.config.get('SERVER_NAME') is None:
            self.config['SERVER_NAME'] = configuration.get_optional_str('flask_server_name')
        self.config['menu'] = []
        self.config['js_url'] = ''
        self.config['css_url'] = ''
        self.config['commit-id'] = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode()
        self.config['branch'] = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip().decode()
        self.config['SESSION_COOKIE_DOMAIN'] = configuration.get_optional_str('flask_cookie_domain')

        translations = os.path.abspath(os.path.join(shared_web_path, 'translations'))
        self.config['BABEL_TRANSLATION_DIRECTORIES'] = translations
        self.babel = Babel(self)
        localization.init(self.babel)
        self.api_root = Blueprint('api', import_name, url_prefix='/api/')
        self.api = Api(self.api_root, title=f'{import_name} API')
        self.register_blueprint(self.api_root) 
Example #18
Source File: test_index.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def test_menu_logged_in_error_dont_show_user_loaded(self, mock_user_get):
        """ If the user is logged in, if we show a 500 error, do not show the user menu
        If the user has previously been loaded in the view, check that it's not
        loaded while rendering the template"""

        user = db_user.get_or_create(1, 'iliekcomputers')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        user = db_user.get_or_create(1, 'iliekcomputers')

        mock_user_get.return_value = user

        @self.app.route('/page_that_returns_500')
        @login_required
        def view500():
            # flask-login user is loaded during @login_required, so check that the db has been queried
            mock_user_get.assert_called_with(user['login_id'])
            raise InternalServerError('error')

        self.temporary_login(user['login_id'])
        resp = self.client.get('/page_that_returns_500')
        data = resp.data.decode('utf-8')
        self.assertIn('Import', data)
        # item not in user menu
        self.assertNotIn('My Listens', data)
        self.assertNotIn('Sign in', data)
        # Even after rendering the template, the database has only been queried once (before the exception)
        mock_user_get.assert_called_once()
        self.assertIsInstance(self.get_context_variable('current_user'), listenbrainz.webserver.login.User) 
Example #19
Source File: test_index.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def test_current_status_ise(self, mock_rabbitmq_connection_module):
        mock_rabbitmq_connection_module._rabbitmq.get.side_effect = InternalServerError
        r = self.client.get(url_for('index.current_status'))
        self.assert500(r)

        mock_rabbitmq_connection_module._rabbitmq.get.side_effect = ConnectionClosed
        r = self.client.get(url_for('index.current_status'))
        self.assert200(r)

        mock_rabbitmq_connection_module._rabbitmq.get.side_effect = ConnectionClosed
        r = self.client.get(url_for('index.current_status'))
        self.assert200(r) 
Example #20
Source File: error.py    From huskar with MIT License 5 votes vote down vote up
def handle_unknown_error(error):
    return handle_http_error(InternalServerError()) 
Example #21
Source File: error.py    From huskar with MIT License 5 votes vote down vote up
def http_errorhandler(fn):
    def iter_derived_classes(base_class):
        for class_ in base_class.__subclasses__():
            yield class_
            for derived_class in iter_derived_classes(class_):
                yield derived_class

    for http_error in iter_derived_classes(HTTPException):
        if http_error is InternalServerError:
            continue
        bp.app_errorhandler(http_error)(fn)
    return fn 
Example #22
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_responds_with_validate(app, client):  # noqa
    import pytest
    from flask import jsonify
    from werkzeug.exceptions import InternalServerError

    class TestDataObj:
        def __init__(self, wrong_field, name):
            self.wrong_field = wrong_field
            self.name = name

    class TestSchema(Schema):
        _id = fields.Integer(required=True)
        name = fields.String(required=True)

    @app.errorhandler(InternalServerError)
    def payload_validation_failure(err):
        return jsonify({"message": "Server attempted to return invalid data"}), 500

    @app.route("/test")
    @responds(schema=TestSchema, validate=True)
    def get():
        obj = {"wrong_field": 42, "name": "Jon Snow"}
        data = TestDataObj(**obj)
        return data

    with app.test_client() as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert resp.status_code == 500
        assert resp.json == {"message": "Server attempted to return invalid data"} 
Example #23
Source File: login.py    From votr with Apache License 2.0 5 votes vote down vote up
def proxylogin(request):
    if request.remote_user is None:
        raise InternalServerError(
            '/proxylogin is supposed to have "CosignAllowPublicAccess Off"')

    return finish_login(request, request.args['destination'],
        dict(type='cosignproxy', server=request.args['server'])) 
Example #24
Source File: http.py    From prometheus-pve-exporter with Apache License 2.0 5 votes vote down vote up
def view(self, endpoint, values, args):
        """
        Werkzeug views mapping method.
        """

        params = dict(values)
        if endpoint in self._args:
            params.update({key: args[key] for key in self._args[endpoint] if key in args})

        try:
            return self._views[endpoint](**params)
        except Exception as error:  # pylint: disable=broad-except
            self._log.exception("Exception thrown while rendering view")
            self._errors.labels(args.get('module', 'default')).inc()
            raise InternalServerError(error) 
Example #25
Source File: test_error_handler.py    From flask-smorest with MIT License 5 votes vote down vote up
def test_error_handler_on_unhandled_error(self, app):

        client = app.test_client()

        @app.route('/uncaught')
        def test_uncaught():
            raise Exception('Oops, something really bad happened.')

        Api(app)

        response = client.get('/uncaught')
        assert response.status_code == 500
        assert response.json['code'] == 500
        assert response.json['status'] == InternalServerError().name 
Example #26
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def handle_exception(e):
        log.debug('LDAP server not accessible while trying to login to opds feed')
        return error_http(FailedDependency())

# @app.errorhandler(InvalidRequestError)
#@app.errorhandler(OperationalError)
#def handle_db_exception(e):
#    db.session.rollback()
#    log.error('Database request error: %s',e)
#    return internal_error(InternalServerError(e)) 
Example #27
Source File: main.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def image(c: str = '') -> wrappers.Response:
    names = c.split('|')
    try:
        requested_cards = oracle.load_cards(names)
        path = image_fetcher.download_image(requested_cards)
        if path is None:
            raise InternalServerError(f'Failed to get image for {c}')
        return send_file(os.path.abspath(path)) # Send abspath to work around monolith root versus web root.
    except TooFewItemsException as e:
        logger.info(f'Did not find an image for {c}: {e}')
        if len(names) == 1:
            return redirect(f'https://api.scryfall.com/cards/named?exact={c}&format=image', code=303)
        return make_response('', 400) 
Example #28
Source File: flask_app.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def internal_server_error(self, e: Exception) -> Union[Tuple[str, int], Response]:
        log_exception(request, e)
        path = request.path
        try:
            repo.create_issue('500 error at {path}\n {e}'.format(path=path, e=e), session.get('mtgo_username', session.get('id', 'logged_out')), self.name, 'PennyDreadfulMTG/perf-reports', exception=e)
        except GithubException:
            logger.error('Github error', e)
        if request.path.startswith('/api/'):
            return return_json(generate_error('INTERNALERROR', 'Internal Error.', exception=e), status=404)
        view = InternalServerError(e)
        return view.page(), 500 
Example #29
Source File: skill_adapter.py    From alexa-skills-kit-sdk-for-python with Apache License 2.0 4 votes vote down vote up
def dispatch_request(self):
        # type: () -> Response
        """Method that handles request verification and routing.

        This method can be used as a function to register on the URL
        rule. The request is verified through the registered list of
        verifiers, before invoking the request handlers. The method
        returns a JSON response for the Alexa service to respond to the
        request.

        :return: The skill response for the input request
        :rtype: flask.Response
        :raises: :py:class:`werkzeug.exceptions.MethodNotAllowed` if the
            method is invoked for other than HTTP POST request.
            :py:class:`werkzeug.exceptions.BadRequest` if the
            verification fails.
            :py:class:`werkzeug.exceptions.InternalServerError` for any
            internal exception.
        """
        if flask_request.method != "POST":
            raise exceptions.MethodNotAllowed()

        if self._webservice_handler is None:
            raise AskSdkException("app not configured with skill handlers")

        try:
            content = flask_request.data.decode(
                verifier_constants.CHARACTER_ENCODING)
            response = self._webservice_handler.verify_request_and_dispatch(
                http_request_headers=typing.cast(
                    typing.Dict[str, typing.Any], flask_request.headers),
                http_request_body=content)

            return jsonify(response)
        except VerificationException:
            current_app.logger.error(
                "Request verification failed", exc_info=True)
            raise exceptions.BadRequest(
                description="Incoming request failed verification")
        except AskSdkException:
            current_app.logger.error(
                "Skill dispatch exception", exc_info=True)
            raise exceptions.InternalServerError(
                description="Exception occurred during skill dispatch")