Python http.HTTPStatus.BAD_REQUEST Examples
The following are 30
code examples of http.HTTPStatus.BAD_REQUEST().
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 |
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: validation_error_handler.py From flasgger with MIT License | 6 votes |
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))
Example #3
Source File: teams_activity_handler.py From botbuilder-python with MIT License | 6 votes |
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.", )
Example #4
Source File: teams_activity_handler.py From botbuilder-python with MIT License | 6 votes |
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", )
Example #5
Source File: testing_farm.py From packit-service with MIT License | 6 votes |
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
Example #6
Source File: routes.py From dffml with MIT License | 6 votes |
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)
Example #7
Source File: endpoints.py From video-analytics-serving with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source File: endpoints.py From video-analytics-serving with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #9
Source File: endpoints.py From video-analytics-serving with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #10
Source File: __init__.py From amundsenmetadatalibrary with Apache License 2.0 | 6 votes |
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
Example #11
Source File: users.py From asgard-api with MIT License | 6 votes |
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 )
Example #12
Source File: jobs.py From asgard-api with MIT License | 6 votes |
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
Example #13
Source File: request_filter.py From openbrokerapi with MIT License | 6 votes |
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
Example #14
Source File: test_httpservers.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_version_digits(self): self.con._http_vsn_str = 'HTTP/9.9.9' self.con.putrequest('GET', '/') self.con.endheaders() res = self.con.getresponse() self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Example #15
Source File: validation_error_handler.py From flasgger with MIT License | 5 votes |
def validation_error_inform_error(err, data, schema): """ Custom validation error handler which produces 404 Bad Request response in case validation fails and returns the error """ abort(Response( json.dumps({'error': str(err), 'data': data, 'schema': schema}), status=HTTPStatus.BAD_REQUEST))
Example #16
Source File: request_filter.py From openbrokerapi with MIT License | 5 votes |
def check_version(): from flask import request version = request.headers.get("X-Broker-Api-Version", None) if not version: return to_json_response(ErrorResponse(description="No X-Broker-Api-Version found.")), HTTPStatus.BAD_REQUEST if MIN_VERSION > version_tuple(version): return to_json_response(ErrorResponse( description="Service broker requires version %d.%d+." % MIN_VERSION) ), HTTPStatus.PRECONDITION_FAILED
Example #17
Source File: request_filter.py From openbrokerapi with MIT License | 5 votes |
def requires_application_json(f): """Decorator for enforcing application/json Content-Type""" @functools.wraps(f) def wrapped(*args, **kwargs): from flask import request if request.get_json(silent=True) is None: er = ErrorResponse(description='Improper Content-Type header. Expecting "application/json"') return to_json_response(er), HTTPStatus.BAD_REQUEST else: return f(*args, **kwargs) return wrapped
Example #18
Source File: responses.py From maubot with GNU Affero General Public License v3.0 | 5 votes |
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)
Example #19
Source File: test_utils.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def test_http_status_to_canonical_code(self): for status_code, expected in ( (HTTPStatus.OK, StatusCanonicalCode.OK), (HTTPStatus.ACCEPTED, StatusCanonicalCode.OK), (HTTPStatus.IM_USED, StatusCanonicalCode.OK), (HTTPStatus.MULTIPLE_CHOICES, StatusCanonicalCode.OK), (HTTPStatus.BAD_REQUEST, StatusCanonicalCode.INVALID_ARGUMENT), (HTTPStatus.UNAUTHORIZED, StatusCanonicalCode.UNAUTHENTICATED), (HTTPStatus.FORBIDDEN, StatusCanonicalCode.PERMISSION_DENIED), (HTTPStatus.NOT_FOUND, StatusCanonicalCode.NOT_FOUND), ( HTTPStatus.UNPROCESSABLE_ENTITY, StatusCanonicalCode.INVALID_ARGUMENT, ), ( HTTPStatus.TOO_MANY_REQUESTS, StatusCanonicalCode.RESOURCE_EXHAUSTED, ), (HTTPStatus.NOT_IMPLEMENTED, StatusCanonicalCode.UNIMPLEMENTED), (HTTPStatus.SERVICE_UNAVAILABLE, StatusCanonicalCode.UNAVAILABLE), ( HTTPStatus.GATEWAY_TIMEOUT, StatusCanonicalCode.DEADLINE_EXCEEDED, ), ( HTTPStatus.HTTP_VERSION_NOT_SUPPORTED, StatusCanonicalCode.INTERNAL, ), (600, StatusCanonicalCode.UNKNOWN), (99, StatusCanonicalCode.UNKNOWN), ): with self.subTest(status_code=status_code): actual = http_status_to_canonical_code(int(status_code)) self.assertEqual(actual, expected, status_code)
Example #20
Source File: test_reposcan.py From vmaas with GNU General Public License v2.0 | 5 votes |
def test_add_repo_2(self): """Test add repo - bad request.""" body = """[{"wrong_key: {}"}]""" resp = self.fetch('/api/v1/repos', method='POST', data=body) self.assertEqual(HTTPStatus.BAD_REQUEST, resp.status)
Example #21
Source File: test_app.py From vmaas with GNU General Public License v2.0 | 5 votes |
def test_error_formatter(self): """Test error formater""" resp = await self.fetch('/api/v1/cves/*', method='GET') assert HTTPStatus.BAD_REQUEST == resp.status assert resp.body[24:] == '"detail": "error(\'nothing to repeat at position 1\',)", "status": 400}'
Example #22
Source File: test_app.py From vmaas with GNU General Public License v2.0 | 5 votes |
def test_updates_post_2_short(self): """Test updates post endpoint.""" body = """{"package_list": []}""" resp = await self.fetch('/api/v1/updates', method='POST', data=body) assert HTTPStatus.BAD_REQUEST == resp.status assert resp.body[48:92] == '"detail": "[] is too short - \'package_list\'"'
Example #23
Source File: test_http_client.py From asgard-api with MIT License | 5 votes |
def test_raise_bad_request_exception_when_response_is_400(self): client = HttpClient() url = "https://httpbin.org/status/400" try: await client.get(url) except HTTPBadRequest as e: self.assertEqual(HTTPStatus.BAD_REQUEST, e.status) self.assertEqual(url, str(e.request_info.url)) self.assertEqual("GET", e.request_info.method) self.assertIsNotNone(e.request_info.headers)
Example #24
Source File: test_chronos_scheduled_jobs_backend.py From asgard-api with MIT License | 5 votes |
def test_delete_job_exist_when_get_does_not_exist_when_delete(self): """ A lógica do delete é: get_by_id() se não existe, retorna Erro se existe, apaga. Esse teste valida que, se o job for removido *entre* as chamadas do get_by_id() e o delete(), ainda assim conseguimos retornar com se o job tivesse sido removido por nós. """ self.asgard_job.remove_namespace(self.account) CHRONOS_BASE_URL = ( f"{settings.SCHEDULED_JOBS_SERVICE_ADDRESS}/v1/scheduler" ) with aioresponses() as rsps: rsps.get( f"{CHRONOS_BASE_URL}/job/{self.chronos_dev_job_fixture['name']}", payload=self.chronos_dev_job_fixture, ) rsps.get( f"{CHRONOS_BASE_URL}/job/{self.chronos_dev_job_fixture['name']}", exception=HTTPNotFound(request_info=None), ) rsps.delete( f"{CHRONOS_BASE_URL}/job/{self.chronos_dev_job_fixture['name']}", status=HTTPStatus.BAD_REQUEST, ) deleted_job = await self.backend.delete_job( self.asgard_job, self.user, self.account ) self.assertEqual(self.asgard_job.dict(), deleted_job.dict()) not_found_job = await self.backend.get_job_by_id( self.asgard_job.id, self.user, self.account ) self.assertIsNone(not_found_job)
Example #25
Source File: test_jobs.py From asgard-api with MIT License | 5 votes |
def test_create_job_invalid_input(self): """ Retornamos HTTPStatus.BAD_REQUEST caso a entrada não seja um JSON válido """ resp = await self.client.post( "/jobs", headers={ "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}" }, data="{data", ) self.assertEqual(HTTPStatus.BAD_REQUEST, resp.status)
Example #26
Source File: test_apps.py From asgard-api with MIT License | 5 votes |
def tearDown(self): await super(AppStatsTest, self).tearDown() await self.esclient.indices.delete( index=self.INDEX_NAME, ignore=[HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND], )
Example #27
Source File: client.py From asgard-api with MIT License | 5 votes |
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 #28
Source File: responses.py From maubot with GNU Affero General Public License v3.0 | 5 votes |
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)
Example #29
Source File: responses.py From maubot with GNU Affero General Public License v3.0 | 5 votes |
def plugin_import_error(error: str, stacktrace: str) -> web.Response: return web.json_response({ "error": error, "stacktrace": stacktrace, "errcode": "plugin_invalid", }, status=HTTPStatus.BAD_REQUEST)
Example #30
Source File: apps.py From cf-python-client with Apache License 2.0 | 5 votes |
def _safe_get_instances(self, application_guid: str) -> JsonObject: try: return self.get_instances(application_guid) except InvalidStatusCode as ex: if ex.status_code == HTTPStatus.BAD_REQUEST and type(ex.body) == dict: code = ex.body.get('code', -1) # 170002: staging not finished # 220001: instances error if code == 220001 or code == 170002: return JsonObject() else: _logger.error("") raise