當前位置: 首頁>>代碼示例>>Python>>正文


Python HTTPStatus.INTERNAL_SERVER_ERROR屬性代碼示例

本文整理匯總了Python中http.HTTPStatus.INTERNAL_SERVER_ERROR屬性的典型用法代碼示例。如果您正苦於以下問題:Python HTTPStatus.INTERNAL_SERVER_ERROR屬性的具體用法?Python HTTPStatus.INTERNAL_SERVER_ERROR怎麽用?Python HTTPStatus.INTERNAL_SERVER_ERROR使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在http.HTTPStatus的用法示例。


在下文中一共展示了HTTPStatus.INTERNAL_SERVER_ERROR屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: register

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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) 
開發者ID:maubot,項目名稱:maubot,代碼行數:26,代碼來源:client_auth.py

示例2: broad_exception_handler

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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 
開發者ID:JoMingyu,項目名稱:Flask-Large-Application-Example,代碼行數:23,代碼來源:error.py

示例3: _send_message

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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) 
開發者ID:PacktPublishing,項目名稱:Python-Programming-Blueprints,代碼行數:23,代碼來源:app.py

示例4: do_GET

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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) 
開發者ID:flyingcircusio,項目名稱:vulnix,代碼行數:20,代碼來源:conftest.py

示例5: pipelines_name_version_get

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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) 
開發者ID:intel,項目名稱:video-analytics-serving,代碼行數:25,代碼來源:endpoints.py

示例6: pipelines_name_version_instance_id_delete

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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) 
開發者ID:intel,項目名稱:video-analytics-serving,代碼行數:27,代碼來源:endpoints.py

示例7: pipelines_name_version_instance_id_get

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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) 
開發者ID:intel,項目名稱:video-analytics-serving,代碼行數:27,代碼來源:endpoints.py

示例8: test_unsuccessful_request

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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() 
開發者ID:b2wdigital,項目名稱:async-worker,代碼行數:23,代碼來源:test_http_metrics.py

示例9: test_raise_and_log_if_types_mismtach

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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",
                    }
                ) 
開發者ID:b2wdigital,項目名稱:async-worker,代碼行數:24,代碼來源:test_http_decorators.py

示例10: insert_role

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'):
    """Creates and inserts a new GSuite Admin Role.

    Args:
      name: str, the name of the new GSuite Admin Role.
      customer_id: str, the G Suite customer ID to insert the role into.

    Returns:
      A dictionary object representing the new GSuite Admin Role.
          https://developers.google.com/admin-sdk/directory/v1/reference/roles

    Raises:
      AlreadyExistsError: when the role with the provided name already exists.
      ForbiddenError: when authorization fails.
      InsertionError: when creation fails (e.g. failed to authenticate, improper
          scopes, etc).
    """
    try:
      return self._client.roles().insert(
          customer=customer_id,
          body={
              'roleName': name,
              'rolePrivileges': _ROLE_PRIVILEGES,
              'roleDescription': _ROLE_DESCRIPTION,
              'isSystemRole': False,
              'isSuperAdminRole': False,
          },
      ).execute()
    except errors.HttpError as err:
      status = err.resp.status

      if (status == http_status.CONFLICT or
          status == http_status.INTERNAL_SERVER_ERROR):
        raise AlreadyExistsError(
            'role with name {!r} already exists'.format(name))

      if status == http_status.FORBIDDEN:
        raise ForbiddenError(_FORBIDDEN_ERROR_MSG)

      logging.error(_INSERT_ROLE_ERROR_MSG, name, err)
      raise InsertionError(_INSERT_ROLE_ERROR_MSG % (name, err)) 
開發者ID:google,項目名稱:loaner,代碼行數:43,代碼來源:directory.py

示例11: _check_status

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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))) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:38,代碼來源:webserver.py

示例12: internal_error_attachment

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
def internal_error_attachment():
    """A 500 error with Content-Disposition: inline."""
    response = flask.Response(b"", headers={
        "Content-Type": "application/octet-stream",
        "Content-Disposition": 'inline; filename="attachment.jpg"',
    })
    response.status_code = HTTPStatus.INTERNAL_SERVER_ERROR
    return response 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:10,代碼來源:webserver_sub.py

示例13: internal_error

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
def internal_error():
    """A normal 500 error."""
    r = flask.make_response()
    r.status_code = HTTPStatus.INTERNAL_SERVER_ERROR
    return r 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:7,代碼來源:webserver_sub.py

示例14: plugin_reload_error

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
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) 
開發者ID:maubot,項目名稱:maubot,代碼行數:8,代碼來源:responses.py

示例15: internal_server_error

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import INTERNAL_SERVER_ERROR [as 別名]
def internal_server_error(self) -> web.Response:
        return web.json_response({
            "error": "Internal server error",
            "errcode": "internal_server_error",
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
開發者ID:maubot,項目名稱:maubot,代碼行數:7,代碼來源:responses.py


注:本文中的http.HTTPStatus.INTERNAL_SERVER_ERROR屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。