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


Python HTTPStatus.BAD_REQUEST屬性代碼示例

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


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

示例1: on_teams_file_consent

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def on_teams_file_consent(
        self,
        turn_context: TurnContext,
        file_consent_card_response: FileConsentCardResponse,
    ) -> InvokeResponse:
        if file_consent_card_response.action == "accept":
            await self.on_teams_file_consent_accept(
                turn_context, file_consent_card_response
            )
            return self._create_invoke_response()

        if file_consent_card_response.action == "decline":
            await self.on_teams_file_consent_decline(
                turn_context, file_consent_card_response
            )
            return self._create_invoke_response()

        raise _InvokeResponseException(
            HTTPStatus.BAD_REQUEST,
            f"{file_consent_card_response.action} is not a supported Action.",
        ) 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:23,代碼來源:teams_activity_handler.py

示例2: on_teams_messaging_extension_submit_action_dispatch

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def on_teams_messaging_extension_submit_action_dispatch(
        self, turn_context: TurnContext, action: MessagingExtensionAction
    ) -> MessagingExtensionActionResponse:
        if not action.bot_message_preview_action:
            return await self.on_teams_messaging_extension_submit_action(
                turn_context, action
            )

        if action.bot_message_preview_action == "edit":
            return await self.on_teams_messaging_extension_bot_message_preview_edit(
                turn_context, action
            )

        if action.bot_message_preview_action == "send":
            return await self.on_teams_messaging_extension_bot_message_preview_send(
                turn_context, action
            )

        raise _InvokeResponseException(
            status_code=HTTPStatus.BAD_REQUEST,
            body=f"{action.bot_message_preview_action} is not a supported BotMessagePreviewAction",
        ) 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:24,代碼來源:teams_activity_handler.py

示例3: broad_exception_handler

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [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

示例4: post

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def post(self):
        """
        Submit Testing Farm results
        """
        msg = request.json

        if not msg:
            logger.debug("/testing-farm/results: we haven't received any JSON data.")
            return "We haven't received any JSON data.", HTTPStatus.BAD_REQUEST

        try:
            self.validate_testing_farm_request()
        except ValidationFailed as exc:
            logger.info(f"/testing-farm/results {exc}")
            return str(exc), HTTPStatus.UNAUTHORIZED

        celery_app.send_task(
            name="task.steve_jobs.process_message", kwargs={"event": msg}
        )

        return "Test results accepted", HTTPStatus.ACCEPTED 
開發者ID:packit-service,項目名稱:packit-service,代碼行數:23,代碼來源:testing_farm.py

示例5: multicomm_register

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def multicomm_register(self, request, mcctx):
        config = mcctx.register_config()._fromdict(**(await request.json()))
        if config.output_mode not in self.IO_MODES:
            return web.json_response(
                {
                    "error": f"{config.output_mode!r} is not a valid output_mode option: {self.IO_MODES!r}"
                },
                status=HTTPStatus.BAD_REQUEST,
            )
        self.logger.debug("Register new mutlicomm route: %r", config)
        try:
            await mcctx.register(config)
        except:
            return web.json_response(
                {"error": "In atomic mode, no registrations allowed"},
                status=HTTPStatus.BAD_REQUEST,
            )
        return web.json_response(OK) 
開發者ID:intel,項目名稱:dffml,代碼行數:20,代碼來源:routes.py

示例6: pipelines_name_version_get

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [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

示例7: pipelines_name_version_instance_id_delete

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [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

示例8: pipelines_name_version_instance_id_get

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [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

示例9: get_with_kwargs

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def get_with_kwargs(self, *, id: Optional[str] = None, **kwargs: Optional[Any]) \
            -> Iterable[Union[Mapping, int, None]]:
        if id is not None:
            get_object = getattr(self.client, f'get_{self.str_type}')
            try:
                actual_id: Union[str, int] = int(id) if id.isdigit() else id
                object = get_object(id=actual_id, **kwargs)
                if object is not None:
                    return self.schema().dump(object).data, HTTPStatus.OK
                return None, HTTPStatus.NOT_FOUND
            except ValueError as e:
                return {'message': f'exception:{e}'}, HTTPStatus.BAD_REQUEST
        else:
            get_objects = getattr(self.client, f'get_{self.str_type}s')
            objects: List[Any] = get_objects()
            return self.schema(many=True).dump(objects).data, HTTPStatus.OK 
開發者ID:lyft,項目名稱:amundsenmetadatalibrary,代碼行數:18,代碼來源:__init__.py

示例10: create_user

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def create_user(wrapper: RequestWrapper):
    status_code = HTTPStatus.CREATED
    try:
        user = User(**await wrapper.http_request.json())
    except ValueError:
        return web.json_response(
            UserResource().dict(), status=HTTPStatus.BAD_REQUEST
        )

    try:
        created_user = await UsersService.create_user(user, UsersBackend())
    except DuplicateEntity as de:
        return web.json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(de))]).dict(),
            status=HTTPStatus.UNPROCESSABLE_ENTITY,
        )

    return web.json_response(
        UserResource(user=created_user).dict(), status=status_code
    ) 
開發者ID:b2wdigital,項目名稱:asgard-api,代碼行數:22,代碼來源:users.py

示例11: validate_input

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def validate_input(handler):
    async def _wrapper(wrapper: RequestWrapper):
        try:
            req_body = await wrapper.http_request.json()
        except JSONDecodeError as e:
            return json_response(
                ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
                status=HTTPStatus.BAD_REQUEST,
            )

        try:
            job = ScheduledJob(**req_body)
        except ValidationError as e:
            return json_response(
                ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
                status=HTTPStatus.UNPROCESSABLE_ENTITY,
            )

        wrapper.types_registry.set(job)
        return await call_http_handler(wrapper.http_request, handler)

    return _wrapper 
開發者ID:b2wdigital,項目名稱:asgard-api,代碼行數:24,代碼來源:jobs.py

示例12: check_originating_identity

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def check_originating_identity():
    """
    Check and decode the "X-Broker-API-Originating-Identity" header
    https://github.com/openservicebrokerapi/servicebroker/blob/v2.13/spec.md#originating-identity
    """
    from flask import request, json
    if "X-Broker-API-Originating-Identity" in request.headers:
        try:
            platform, value = request.headers["X-Broker-API-Originating-Identity"].split(None, 1)
            request.originating_identity = {
                'platform': platform,
                'value': json.loads(base64.standard_b64decode(value))
            }
        except ValueError as e:
            return to_json_response(ErrorResponse(
                description='Improper "X-Broker-API-Originating-Identity" header. ' + str(e))
            ), HTTPStatus.BAD_REQUEST
    else:
        request.originating_identity = None 
開發者ID:eruvanos,項目名稱:openbrokerapi,代碼行數:21,代碼來源:request_filter.py

示例13: validation_error_try_to_accept

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def validation_error_try_to_accept(err, data, schema):
    """
    Custom validation error handler which attempts alternative
    validation
    """
    if not isinstance(err, ValidationError):
        abort(Response(err, status=HTTPStatus.BAD_REQUEST))

    alernative_schema = dict(schema)
    alernative_schema['properties']['running_time'].update({
        'description': "Films's running time",
        'type': 'integer',
        'example': 169
    })

    try:
        jsonschema.validate(data, alernative_schema)
    except ValidationError as err:
        abort(Response(str(err), status=400)) 
開發者ID:flasgger,項目名稱:flasgger,代碼行數:21,代碼來源:validation_error_handler.py

示例14: body_not_json

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

示例15: plugin_type_required

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import BAD_REQUEST [as 別名]
def plugin_type_required(self) -> web.Response:
        return web.json_response({
            "error": "Plugin type is required when creating plugin instances",
            "errcode": "plugin_type_required",
        }, status=HTTPStatus.BAD_REQUEST) 
開發者ID:maubot,項目名稱:maubot,代碼行數:7,代碼來源:responses.py


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