Python http.HTTPStatus.INTERNAL_SERVER_ERROR Examples

The following are 30 code examples of http.HTTPStatus.INTERNAL_SERVER_ERROR(). 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 http.HTTPStatus , or try the search function .
Example #1
Source File: error.py    From Flask-Large-Application-Example with MIT License 7 votes vote down vote up
def broad_exception_handler(e: Exception):
    # TODO 에러를 세분화해서 잡는 것을 추천합니다.

    if isinstance(e, HTTPException):
        message = e.description
        code = e.code

    elif isinstance(e, ValidationError):
        message = json.loads(e.json())
        code = HTTPStatus.BAD_REQUEST

    else:
        message = ""
        code = HTTPStatus.INTERNAL_SERVER_ERROR

        if current_app.debug:
            import traceback

            traceback.print_exc()

    return jsonify({"error": message}), code 
Example #2
Source File: test_http_metrics.py    From async-worker with MIT License 6 votes vote down vote up
def test_unsuccessful_request(self):
        url = (
            f"http://{settings.HTTP_HOST}:{settings.HTTP_PORT}{self.route_path}"
        )
        self.callback.side_effect = KeyError
        async with self.client.get(url) as response:
            await response.text()
            self.assertEqual(response.status, HTTPStatus.INTERNAL_SERVER_ERROR)

        self.metrics.response_size.labels.assert_not_called()
        self.metrics.request_duration.labels.assert_called_once_with(
            method=self.route_method,
            path=self.route_path,
            status=response.status,
        )
        self.metrics.requests_in_progress.labels.assert_called_with(
            method=self.route_method, path=self.route_path
        )
        self.metrics.response_size.labels.return_value.observe.assert_not_called()
        self.metrics.request_duration.labels.return_value.observe.assert_called_once()
        self.metrics.requests_in_progress.labels.return_value.dec.assert_called_once() 
Example #3
Source File: endpoints.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pipelines_name_version_instance_id_delete(name, version, instance_id):  # noqa: E501
    """pipelines_name_version_instance_id_delete

    Stop and remove an instance of the customized pipeline # noqa: E501

    :param name:
    :type name: str
    :param version:
    :type version: int
    :param instance_id:
    :type instance_id: int

    :rtype: None
    """
    try:
        logger.debug("DELETE on /pipelines/{name}/{version}/{id}".format(
            name=name, version=version, id=instance_id))
        result = VAServing.pipeline_manager.stop_instance(
            name, version, instance_id)
        if result:
            return result
        return (bad_request_response, HTTPStatus.BAD_REQUEST)
    except Exception as error:
        logger.error('pipelines_name_version_instance_id_delete %s', error)
        return ('Unexpected error', HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #4
Source File: endpoints.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pipelines_name_version_get(name, version):  # noqa: E501
    """pipelines_name_version_get

    Return pipeline description and parameters # noqa: E501

    :param name:
    :type name: str
    :param version:
    :type version: str

    :rtype: None
    """
    try:
        logger.debug(
            "GET on /pipelines/{name}/{version}".format(name=name, version=version))
        result = VAServing.pipeline_manager.get_pipeline_parameters(
            name, version)
        if result:
            return result
        return ('Invalid Pipeline or Version', HTTPStatus.BAD_REQUEST)
    except Exception as error:
        logger.error('pipelines_name_version_get %s', error)
        return ('Unexpected error', HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #5
Source File: endpoints.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pipelines_name_version_instance_id_get(name, version, instance_id):  # noqa: E501
    """pipelines_name_version_instance_id_get

    Return instance summary # noqa: E501

    :param name:
    :type name: str
    :param version:
    :type version: int
    :param instance_id:
    :type instance_id: int

    :rtype: object
    """
    try:
        logger.debug("GET on /pipelines/{name}/{version}/{id}".format(
            name=name, version=version, id=instance_id))
        result = VAServing.pipeline_manager.get_instance_parameters(
            name, version, instance_id)
        if result:
            return result
        return (bad_request_response, HTTPStatus.BAD_REQUEST)
    except Exception as error:
        logger.error('pipelines_name_version_instance_id_get %s', error)
        return ('Unexpected error', HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #6
Source File: conftest.py    From vulnix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_GET(self):
        """Serve a GET request from the fixtures directory"""
        fn = p.join(p.dirname(__file__), 'fixtures', self.path[1:])
        print("path=", fn)
        try:
            with open(fn, 'rb') as f:
                stat = os.fstat(f.fileno())
                content = f.read()
        except OSError:
            self.send_error(HTTPStatus.NOT_FOUND)
        except IOError:
            self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR)
        self.send_response(HTTPStatus.OK)
        self.send_header('Content-Type', self.guess_type(fn))
        self.send_header('Content-Length', stat.st_size)
        self.send_header('ETag', hashlib.sha1(content).hexdigest())
        self.end_headers()
        self.wfile.write(content) 
Example #7
Source File: app.py    From Python-Programming-Blueprints with MIT License 6 votes vote down vote up
def _send_message(message):

    smtp = smtplib.SMTP_SSL('email-smtp.eu-west-1.amazonaws.com', 465)

    try:
        smtp.login(
            user='AKIAITZ6BSMD7DMZYTYQ',
            password='Ajf0ucUGJiN44N6IeciTY4ApN1os6JCeQqyglRSI2x4V')
    except SMTPAuthenticationError:
        return Response('Authentication failed',
                        status=HTTPStatus.UNAUTHORIZED)

    try:
        smtp.sendmail(message['From'], message['To'], message.as_string())
    except SMTPRecipientsRefused as e:
        return Response(f'Recipient refused {e}',
                        status=HTTPStatus.INTERNAL_SERVER_ERROR)
    finally:
        smtp.quit()

    return Response('Email sent', status=HTTPStatus.OK) 
Example #8
Source File: client_auth.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def register(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, secret, username, password, user_type = info
    res = await api.request(Method.GET, Path.admin.register)
    nonce = res["nonce"]
    mac = generate_mac(secret, nonce, username, password, user_type=user_type)
    try:
        return web.json_response(await api.request(Method.POST, Path.admin.register, content={
            "nonce": nonce,
            "username": username,
            "password": password,
            "admin": False,
            "mac": mac,
            # Older versions of synapse will ignore this field if it is None
            "user_type": user_type,
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
            "http_status": e.http_status,
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #9
Source File: test_http_decorators.py    From async-worker with MIT License 6 votes vote down vote up
def test_raise_and_log_if_types_mismtach(self):
        """
        Se declararmos o argumento de um tipo inconpatível com o valor recebido
        lançamos uma exceção.
        Devemos gerar um logger.exception()
        """
        logger_mock_template = mock.CoroutineMock(
            exception=mock.CoroutineMock()
        )
        with mock.patch.object(
            decorators, "logger", logger_mock_template
        ) as logger_mock:
            async with HttpClientContext(self.app) as client:
                resp = await client.post("/get_by_id/abc")
                self.assertEqual(HTTPStatus.INTERNAL_SERVER_ERROR, resp.status)
                logger_mock.exception.assert_awaited_with(
                    {
                        "event": "incompatible-types-handler-arg",
                        "arg-type": int,
                        "arg-value": "abc",
                    }
                ) 
Example #10
Source File: webserver.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def _check_status(self):
        """Check if the http status is what we expected."""
        path_to_statuses = {
            '/favicon.ico': [HTTPStatus.OK, HTTPStatus.PARTIAL_CONTENT],

            '/does-not-exist': [HTTPStatus.NOT_FOUND],
            '/does-not-exist-2': [HTTPStatus.NOT_FOUND],
            '/404': [HTTPStatus.NOT_FOUND],

            '/redirect-later': [HTTPStatus.FOUND],
            '/redirect-self': [HTTPStatus.FOUND],
            '/redirect-to': [HTTPStatus.FOUND],
            '/relative-redirect': [HTTPStatus.FOUND],
            '/absolute-redirect': [HTTPStatus.FOUND],

            '/cookies/set': [HTTPStatus.FOUND],

            '/500-inline': [HTTPStatus.INTERNAL_SERVER_ERROR],
            '/500': [HTTPStatus.INTERNAL_SERVER_ERROR],
        }
        for i in range(15):
            path_to_statuses['/redirect/{}'.format(i)] = [HTTPStatus.FOUND]
        for suffix in ['', '1', '2', '3', '4', '5', '6']:
            key = ('/basic-auth/user{suffix}/password{suffix}'
                   .format(suffix=suffix))
            path_to_statuses[key] = [HTTPStatus.UNAUTHORIZED, HTTPStatus.OK]

        default_statuses = [HTTPStatus.OK, HTTPStatus.NOT_MODIFIED]

        sanitized = QUrl('http://localhost' + self.path).path()  # Remove ?foo
        expected_statuses = path_to_statuses.get(sanitized, default_statuses)
        if self.status not in expected_statuses:
            raise AssertionError(
                "{} loaded with status {} but expected {}".format(
                    sanitized, self.status,
                    ' / '.join(repr(e) for e in expected_statuses))) 
Example #11
Source File: test_http_client.py    From asgard-api with MIT License 5 votes vote down vote up
def test_raise_internal_error_exception_when_response_is_500(self):
        client = HttpClient()
        url = "https://httpbin.org/status/500"

        try:
            await client.get(url)
        except HTTPInternalServerError as e:
            self.assertEqual(HTTPStatus.INTERNAL_SERVER_ERROR, e.status)
            self.assertEqual(url, str(e.request_info.url))
            self.assertEqual("GET", e.request_info.method)
            self.assertIsNotNone(e.request_info.headers) 
Example #12
Source File: client.py    From asgard-api with MIT License 5 votes vote down vote up
def _request(
        self,
        method: str,
        url: str,
        headers: Dict[str, str] = {},
        timeout: ClientTimeout = None,
        raise_for_status: bool = True,
        **kwargs: Dict[str, Any],
    ) -> ClientResponse:
        """
        Método que é usado por todos os outros métodos para fazer um request.
        O parametros recebidos por esse métodos definem os parametros recebidos pelo client de uma forma geral.
        """
        try:
            resp = await self._session.request(
                method,
                url,
                headers=headers,
                timeout=timeout,
                raise_for_status=raise_for_status,
                allow_redirects=True,
                **kwargs,
            )
        except ClientResponseError as ce:
            if ce.status == HTTPStatus.NOT_FOUND:
                raise HTTPNotFound(request_info=ce.request_info)
            if ce.status == HTTPStatus.INTERNAL_SERVER_ERROR:
                raise HTTPInternalServerError(request_info=ce.request_info)
            if ce.status == HTTPStatus.BAD_REQUEST:
                raise HTTPBadRequest(request_info=ce.request_info)
            raise ce

        return resp 
Example #13
Source File: test_search_dashboard_api.py    From amundsensearchlibrary with Apache License 2.0 5 votes vote down vote up
def test_should_fail_when_proxy_fails(self) -> None:
        self.mock_proxy.fetch_dashboard_search_results.side_effect = RuntimeError('search failed')

        response = self.app.test_client().get('/search_dashboard?query_term=searchterm')

        self.assertEqual(response.status_code, HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #14
Source File: test_table_owner_api.py    From amundsenmetadatalibrary with Apache License 2.0 5 votes vote down vote up
def test_should_fail_when_delete_owner_fails(self) -> None:
        self.mock_proxy.delete_owner.side_effect = RuntimeError()

        response = self.app.test_client().delete(f'/table/{TABLE_URI}/owner/{OWNER}')

        self.assertEqual(response.status_code, HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #15
Source File: test_table_owner_api.py    From amundsenmetadatalibrary with Apache License 2.0 5 votes vote down vote up
def test_should_fail_when_owner_update_fails(self) -> None:
        self.mock_proxy.add_owner.side_effect = RuntimeError()

        response = self.app.test_client().put(f'/table/{TABLE_URI}/owner/{OWNER}')

        self.assertEqual(response.status_code, HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #16
Source File: test_table_description_api.py    From amundsenmetadatalibrary with Apache License 2.0 5 votes vote down vote up
def test_should_fail_when_cannot_get_description(self) -> None:
        self.mock_proxy.get_table_description.side_effect = RuntimeError()

        response = self.app.test_client().get(f'/table/{TABLE_URI}/description')

        self.assertEqual(response.status_code, HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #17
Source File: test_column_description_api.py    From amundsenmetadatalibrary with Apache License 2.0 5 votes vote down vote up
def test_should_fail_to_get_column_description(self) -> None:
        self.mock_proxy.get_column_description.side_effect = RuntimeError

        response = self.app.test_client().get(f'/table/{TABLE_NAME}/column/{COLUMN_NAME}/description')

        self.assertEqual(response.status_code, HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #18
Source File: test_search_table_api.py    From amundsensearchlibrary with Apache License 2.0 5 votes vote down vote up
def test_should_fail_when_proxy_fails(self) -> None:
        self.mock_proxy.fetch_table_search_results.side_effect = RuntimeError('search failed')

        response = self.app.test_client().get('/search?query_term=searchterm')

        self.assertEqual(response.status_code, HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #19
Source File: aiohttp_resources.py    From async-worker with MIT License 5 votes vote down vote up
def http_metrics_middleware(request: web.Request, handler: _Handler):
    start = now()
    try:
        metrics.requests_in_progress.labels(
            method=request.method, path=request.path
        ).inc()
        response = await handler(request)
        metrics.response_size.labels(
            method=request.method, path=request.path
        ).observe(response.content_length)
        metrics.request_duration.labels(
            method=request.method, path=request.path, status=response.status
        ).observe(now() - start)

        return response
    except web.HTTPException as e:
        metrics.request_duration.labels(
            method=request.method, path=request.path, status=e.status
        ).observe(now() - start)
        metrics.response_size.labels(
            method=request.method, path=request.path
        ).observe(e.content_length)
        raise e
    except Exception as e:
        metrics.request_duration.labels(
            method=request.method,
            path=request.path,
            status=HTTPStatus.INTERNAL_SERVER_ERROR,
        ).observe(now() - start)
        raise e
    finally:
        metrics.requests_in_progress.labels(
            method=request.method, path=request.path
        ).dec() 
Example #20
Source File: endpoints.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pipelines_name_version_post(name, version):  # noqa: E501
    """pipelines_name_version_post

    Start new instance of pipeline.
    Specify the source and destination parameters as URIs # noqa: E501

    :param name:
    :type name: str
    :param version:
    :type version: int
    :param pipeline_request:
    :type pipeline_request: dict | bytes

    :rtype: None
    """

    logger.debug(
        "POST on /pipelines/{name}/{version}".format(name=name, version=version))
    if connexion.request.is_json:
        try:
            pipeline_id, err = VAServing.pipeline_manager.create_instance(
                name, version, connexion.request.get_json())
            if pipeline_id is not None:
                return pipeline_id
            return (err, HTTPStatus.BAD_REQUEST)
        except Exception as error:
            logger.error('pipelines_name_version_post %s', error)
            return ('Unexpected error', HTTPStatus.INTERNAL_SERVER_ERROR)

    return('Invalid Request, Body must be valid JSON', HTTPStatus.BAD_REQUEST) 
Example #21
Source File: endpoints.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def models_get():  # noqa: E501
    """models_get

    Return supported models # noqa: E501


    :rtype: List[ModelVersion]
    """
    try:
        logger.debug("GET on /models")
        return VAServing.model_manager.get_loaded_models()
    except Exception as error:
        logger.error('pipelines_name_version_get %s', error)
        return ('Unexpected error', HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #22
Source File: endpoints.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pipelines_get():  # noqa: E501
    """pipelines_get

    Return supported pipelines # noqa: E501


    :rtype: List[Pipeline]
    """
    try:
        logger.debug("GET on /pipelines")
        return VAServing.pipeline_manager.get_loaded_pipelines()
    except Exception as error:
        logger.error('pipelines_name_version_get %s', error)
        return ('Unexpected error', HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #23
Source File: routes.py    From dffml with MIT License 5 votes vote down vote up
def error_middleware(self, request, handler):
        try:
            # HACK This checks if aiohttp's builtin not found handler is going
            # to be called
            # Check if handler is the not found handler
            if "Not Found" in str(handler):
                # Run get_registered_handler to see if we can find the handler
                new_handler = await self.get_registered_handler(request)
                if new_handler is not None:
                    handler = new_handler
            return await handler(request)
        except web.HTTPException as error:
            response = {"error": error.reason}
            if error.text is not None:
                response["error"] = error.text
            return web.json_response(response, status=error.status)
        except Exception as error:  #  pragma: no cov
            self.logger.error(
                "ERROR handling %s: %s",
                request,
                traceback.format_exc().strip(),
            )
            return web.json_response(
                {"error": "Internal Server Error"},
                status=HTTPStatus.INTERNAL_SERVER_ERROR,
            ) 
Example #24
Source File: app.py    From Python-Programming-Blueprints with MIT License 5 votes vote down vote up
def notify_order_shipped():
    data = json.loads(request.data)

    customer = data.get('order_customer')

    customer_email = customer.get('email')
    customer_name = customer.get('name')

    order_id = data.get('id')

    message = MIMEMultipart('alternative')

    try:
        email_content = _prepare_template(
            'order_shipped_template.html',
            {'customer_name': customer_name}
        )
    except S3Error as ex:
        return Response(ex, status=HTTPStatus.INTERNAL_SERVER_ERROR)

    message.attach(MIMEText(email_content, 'html'))

    message['Subject'] = f'Order ID #{order_id} has been shipped'
    message['From'] = 'donotreply@dfurtado.com'
    message['To'] = customer_email

    return _send_message(message) 
Example #25
Source File: app.py    From Python-Programming-Blueprints with MIT License 5 votes vote down vote up
def notify_order_received():
    data = json.loads(request.data)

    order_items = data.get('items')

    customer = data.get('order_customer')
    customer_email = customer.get('email')
    customer_name = customer.get('name')

    order_id = data.get('id')
    total_purchased = data.get('total')

    message = MIMEMultipart('alternative')

    context = {
        'order_items': order_items,
        'customer_name': customer_name,
        'order_id': order_id,
        'total_purchased': total_purchased
    }

    try:
        email_content = _prepare_template(
            'order_received_template.html',
            context
        )
    except S3Error as ex:
        return Response(str(ex), status=HTTPStatus.INTERNAL_SERVER_ERROR)

    message.attach(MIMEText(email_content, 'html'))

    message['Subject'] = f'ORDER: #{order_id} - Thanks for your order!'
    message['From'] = 'donotreply@dfurtado.com'
    message['To'] = customer_email

    return _send_message(message) 
Example #26
Source File: app.py    From portrait-demo with MIT License 5 votes vote down vote up
def handle():
    start = time.time()
    status = HTTPStatus.OK
    result = {'success': False}

    try:
        data = request.json
        if 'image' in data:
            blob = io.BytesIO(base64.b64decode(data['image']))
            img = Image.open(blob).convert('RGB')
        elif 'url' in data:
            blob = io.BytesIO(requests.get(data['url']).content)
            img = Image.open(blob).convert('RGB')
        else:
            raise ValueError(
                f'No image source found in request fields: {data.keys()}')

        mask = segmentator.predict(img)
        mask = (mask * 255).astype(np.uint8)

        fmem = io.BytesIO()
        imsave(fmem, mask, 'png')
        fmem.seek(0)
        mask64 = base64.b64encode(fmem.read()).decode('utf-8')

        result['data'] = {'mask': mask64}
        result['success'] = True
    except Exception as e:
        logger.exception(e)
        result['message'] = str(e)
        status = HTTPStatus.INTERNAL_SERVER_ERROR

    result['total'] = time.time() - start

    return jsonify(result), status 
Example #27
Source File: __init__.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
def handler(e):
        return Response(status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #28
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def invalid_server(self) -> web.Response:
        return web.json_response({
            "error": "Invalid registration server object in maubot configuration",
            "errcode": "invalid_server",
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #29
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def internal_server_error(self) -> web.Response:
        return web.json_response({
            "error": "Internal server error",
            "errcode": "internal_server_error",
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #30
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def plugin_reload_error(error: str, stacktrace: str) -> web.Response:
        return web.json_response({
            "error": error,
            "stacktrace": stacktrace,
            "errcode": "plugin_reload_fail",
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR)