Python http.HTTPStatus() Examples
The following are 30
code examples of http.HTTPStatus().
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
, or try the search function
.
Example #1
Source File: __init__.py From flask-smorest with MIT License | 6 votes |
def _register_responses(self): """Register default responses for all status codes""" # Register a response for each status code for status in http.HTTPStatus: response = { 'description': status.phrase, 'schema': self.ERROR_SCHEMA, } prepare_response( response, self.spec, DEFAULT_RESPONSE_CONTENT_TYPE) self.spec.components.response(status.name, response) # Also register a default error response response = { 'description': 'Default error response', 'schema': self.ERROR_SCHEMA, } prepare_response(response, self.spec, DEFAULT_RESPONSE_CONTENT_TYPE) self.spec.components.response('DEFAULT_ERROR', response)
Example #2
Source File: test_api.py From flask-smorest with MIT License | 6 votes |
def test_api_registers_error_responses(self, app, openapi_version): """Test default error responses are registered""" app.config['OPENAPI_VERSION'] = openapi_version api = Api(app) responses = get_responses(api.spec) assert 'Error' in get_schemas(api.spec) for status in http.HTTPStatus: if openapi_version == '2.0': assert responses[status.name] == { 'description': status.phrase, 'schema': build_ref(api.spec, 'schema', 'Error'), } else: assert responses[status.name] == { 'description': status.phrase, 'content': { 'application/json': { 'schema': build_ref(api.spec, 'schema', 'Error') } } }
Example #3
Source File: test_blueprint.py From flask-smorest with MIT License | 6 votes |
def test_blueprint_arguments_documents_error_response( self, app, schemas, openapi_version, error_code ): app.config['OPENAPI_VERSION'] = openapi_version api = Api(app) blp = Blueprint('test', __name__, url_prefix='/test') blp.ARGUMENTS_PARSER.DEFAULT_VALIDATION_STATUS = 400 kwargs = {} if error_code: kwargs['error_status_code'] = error_code @blp.route('/') @blp.arguments(schemas.DocSchema, **kwargs) def func(): """Dummy view func""" api.register_blueprint(blp) spec = api.spec.to_dict() error_code = error_code or 400 assert ( spec['paths']['/test/']['get']['responses'][str(error_code)] == build_ref(api.spec, 'response', http.HTTPStatus(error_code).name) )
Example #4
Source File: test_blueprint.py From flask-smorest with MIT License | 6 votes |
def test_blueprint_response_description(self, app): api = Api(app) blp = Blueprint('test', 'test', url_prefix='/test') @blp.route('/route_1') @blp.response(code=204) def func_1(): pass @blp.route('/route_2') @blp.response(code=204, description='Test') def func_2(): pass api.register_blueprint(blp) get_1 = api.spec.to_dict()['paths']['/test/route_1']['get'] assert ( get_1['responses']['204']['description'] == http.HTTPStatus(204).phrase ) get_2 = api.spec.to_dict()['paths']['/test/route_2']['get'] assert get_2['responses']['204']['description'] == 'Test'
Example #5
Source File: test_sansio.py From gidgethub with Apache License 2.0 | 6 votes |
def test_422_custom_code(self): status_code = 422 errors = [ { "resource": "PullRequest", "code": "custom", "message": "A pull request already exists for foo:1.", } ] body = json.dumps({"message": "it went bad", "errors": errors}) body = body.encode("utf-8") headers = {"content-type": "application/json; charset=utf-8"} with pytest.raises(ValidationError) as exc_info: sansio.decipher_response(status_code, headers, body) assert exc_info.value.status_code == http.HTTPStatus(status_code) assert ( str(exc_info.value) == "it went bad: 'A pull request already exists for foo:1.'" )
Example #6
Source File: client.py From cf-python-client with Apache License 2.0 | 6 votes |
def _is_token_expired(response: Response) -> bool: if response.status_code == HTTPStatus.UNAUTHORIZED.value: try: json_data = response.json() invalid_token_error = 'CF-InvalidAuthToken' if json_data.get('errors', None) is not None: # V3 error response for error in json_data.get('errors'): if error.get('code', 0) == 1000 and error.get('title', '') == invalid_token_error: _logger.info('_is_token_v3_expired - true') return True _logger.info('_is_token_v3_expired - false') return False else: # V2 error response token_expired = json_data.get('code', 0) == 1000 \ and json_data.get('error_code', '') == invalid_token_error _logger.info('_is_token__v2_expired - %s' % str(token_expired)) return token_expired except Exception as _: return False else: return False
Example #7
Source File: client.py From eureka with Apache License 2.0 | 6 votes |
def _do_req(self, path: str, *, method: str = 'GET', data: Optional[Any] = None): """ Performs a request against the instance eureka server. :param path: URL Path, the hostname is prepended automatically :param method: request method (put/post/patch/get/etc) :param data: Optional data to be sent with the request, must already be encoded appropriately. :return: optional[dict[str, any]] """ url = self._eureka_url + path logger.debug('Performing %s on %s with payload: %s', method, path, data) async with _SESSION.request(method, url, data=data) as resp: if 400 <= resp.status < 600: # noinspection PyArgumentList raise EurekaException(HTTPStatus(resp.status), await resp.text()) logger.debug('Result: %s', resp.status) return await resp.json()
Example #8
Source File: test_endpoint.py From prometheus_flask_exporter with MIT License | 6 votes |
def test_http_status_enum(self): try: from http import HTTPStatus except ImportError: self.skipTest('http.HTTPStatus is not available') metrics = self.metrics() @self.app.route('/no/content') def no_content(): import http return {}, http.HTTPStatus.NO_CONTENT self.client.get('/no/content') self.client.get('/no/content') self.assertMetric( 'flask_http_request_total', '2.0', ('method', 'GET'), ('status', 204) ) self.assertMetric( 'flask_http_request_duration_seconds_count', '2.0', ('method', 'GET'), ('path', '/no/content'), ('status', 204) )
Example #9
Source File: response.py From rssant with BSD 3-Clause "New" or "Revised" License | 6 votes |
def name_of(cls, value): """ >>> FeedResponseStatus.name_of(200) 'OK' >>> FeedResponseStatus.name_of(-200) 'FEED_CONNECTION_ERROR' >>> FeedResponseStatus.name_of(-999) 'FEED_E999' """ if value > 0: try: return HTTPStatus(value).name except ValueError: # eg: http://huanggua.sinaapp.com/ # ValueError: 600 is not a valid HTTPStatus return f'HTTP_{value}' else: try: return 'FEED_' + FeedResponseStatus(value).name except ValueError: return f'FEED_E{abs(value)}'
Example #10
Source File: response.py From rssant with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__( self, *, content: bytes = None, status: int = None, url: str = None, etag: str = None, last_modified: str = None, encoding: str = None, mime_type: str = None, feed_type: FeedContentType = None, use_proxy: bool = None, ): self._content = content self._status = int(status if status is not None else HTTPStatus.OK.value) self._url = url self._encoding = encoding self._etag = etag self._last_modified = last_modified self._mime_type = mime_type self._feed_type = feed_type or FeedContentType.OTHER self._use_proxy = use_proxy
Example #11
Source File: test_exceptions.py From gidgethub with Apache License 2.0 | 5 votes |
def test_RateLimitExceeded(): rate = sansio.RateLimit(limit=1, remaining=0, reset_epoch=1) exc = RateLimitExceeded(rate) assert exc.status_code == http.HTTPStatus.FORBIDDEN exc = RateLimitExceeded(rate, "stuff happened") assert str(exc) == "stuff happened"
Example #12
Source File: test_sansio.py From gidgethub with Apache License 2.0 | 5 votes |
def test_422(self): status_code = 422 errors = [{"resource": "Issue", "field": "title", "code": "missing_field"}] body = json.dumps({"message": "it went bad", "errors": errors}) body = body.encode("utf-8") headers = {"content-type": "application/json; charset=utf-8"} with pytest.raises(InvalidField) as exc_info: sansio.decipher_response(status_code, headers, body) assert exc_info.value.status_code == http.HTTPStatus(status_code) assert str(exc_info.value) == "it went bad for 'title'"
Example #13
Source File: test_exceptions.py From gidgethub with Apache License 2.0 | 5 votes |
def test_RedirectionException(): exc = RedirectionException(http.HTTPStatus.MOVED_PERMANENTLY) assert exc.status_code == http.HTTPStatus.MOVED_PERMANENTLY
Example #14
Source File: test_exceptions.py From gidgethub with Apache License 2.0 | 5 votes |
def test_BadRequest(): exc = BadRequest(http.HTTPStatus.BAD_REQUEST) assert exc.status_code == http.HTTPStatus.BAD_REQUEST
Example #15
Source File: test_exceptions.py From gidgethub with Apache License 2.0 | 5 votes |
def test_BadRequestUnknownError(): exc = BadRequestUnknownError("uh-oh") assert exc.status_code == http.HTTPStatus.UNPROCESSABLE_ENTITY assert exc.response == "uh-oh"
Example #16
Source File: test_sansio.py From gidgethub with Apache License 2.0 | 5 votes |
def test_5XX(self): status_code = 502 with pytest.raises(GitHubBroken) as exc_info: sansio.decipher_response(status_code, {}, b"") assert exc_info.value.status_code == http.HTTPStatus(status_code)
Example #17
Source File: test_exceptions.py From gidgethub with Apache License 2.0 | 5 votes |
def test_GitHubBroken(): exc = GitHubBroken(http.HTTPStatus.BAD_GATEWAY) assert exc.status_code == http.HTTPStatus.BAD_GATEWAY
Example #18
Source File: test_exceptions.py From gidgethub with Apache License 2.0 | 5 votes |
def test_BadGraphQLRequest(): response = {"message": "hello, world"} exc = BadGraphQLRequest(http.HTTPStatus(400), response) assert exc.status_code == http.HTTPStatus(400) assert exc.response == response assert str(exc) == response["message"]
Example #19
Source File: test_exceptions.py From gidgethub with Apache License 2.0 | 5 votes |
def test_GraphQLAuthorizationFailure(): response = {"message": "hello, world"} exc = GraphQLAuthorizationFailure(response) assert exc.response == response assert exc.status_code == http.HTTPStatus(401) assert str(exc) == response["message"]
Example #20
Source File: test_sansio.py From gidgethub with Apache License 2.0 | 5 votes |
def test_403_forbidden(self): status_code = 403 headers = { "content-type": "application/json; charset=utf-8", "x-ratelimit-limit": "2", "x-ratelimit-remaining": "1", "x-ratelimit-reset": "1", } with pytest.raises(BadRequest) as exc_info: sansio.decipher_response(status_code, headers, b"") assert exc_info.value.status_code == http.HTTPStatus(status_code)
Example #21
Source File: test_sansio.py From gidgethub with Apache License 2.0 | 5 votes |
def test_403_rate_limit_exceeded(self): status_code = 403 headers = { "content-type": "application/json; charset=utf-8", "x-ratelimit-limit": "2", "x-ratelimit-remaining": "0", "x-ratelimit-reset": "1", } body = json.dumps({"message": "oops"}).encode("UTF-8") with pytest.raises(RateLimitExceeded) as exc_info: sansio.decipher_response(status_code, headers, body) assert exc_info.value.status_code == http.HTTPStatus(status_code)
Example #22
Source File: test_sansio.py From gidgethub with Apache License 2.0 | 5 votes |
def test_4XX_message(self): status_code = 400 message = json.dumps({"message": "it went bad"}).encode("UTF-8") headers = {"content-type": "application/json; charset=utf-8"} with pytest.raises(BadRequest) as exc_info: sansio.decipher_response(status_code, headers, message) assert exc_info.value.status_code == http.HTTPStatus(status_code) assert str(exc_info.value) == "it went bad"
Example #23
Source File: test_sansio.py From gidgethub with Apache License 2.0 | 5 votes |
def test_4XX_no_message(self): status_code = 400 with pytest.raises(BadRequest) as exc_info: sansio.decipher_response(status_code, {}, b"") assert exc_info.value.status_code == http.HTTPStatus(status_code)
Example #24
Source File: test_abc.py From gidgethub with Apache License 2.0 | 5 votes |
def test_bad_credentials(self): gh, response_data = self.gh_and_response("bad-credentials-401.json") with pytest.raises(GraphQLAuthorizationFailure) as exc: await gh.graphql(_SAMPLE_QUERY) assert exc.value.response == response_data assert exc.value.status_code == http.HTTPStatus(401)
Example #25
Source File: sansio.py From gidgethub with Apache License 2.0 | 5 votes |
def from_http( cls, headers: Mapping[str, str], body: bytes, *, secret: Optional[str] = None ) -> "Event": """Construct an event from HTTP headers and JSON body data. The mapping providing the headers is expected to support lowercase keys. Since this method assumes the body of the HTTP request is JSON, a check is performed for a content-type of "application/json" (GitHub does support other content-types). If the content-type does not match, BadRequest is raised. If the appropriate headers are provided for event validation, then it will be performed unconditionally. Any failure in validation (including not providing a secret) will lead to ValidationFailure being raised. """ if "x-hub-signature" in headers: if secret is None: raise ValidationFailure("secret not provided") validate_event(body, signature=headers["x-hub-signature"], secret=secret) elif secret is not None: raise ValidationFailure("signature is missing") try: data = _decode_body(headers["content-type"], body, strict=True) except (KeyError, ValueError) as exc: raise BadRequest( http.HTTPStatus(415), "expected a content-type of " "'application/json' or " "'application/x-www-form-urlencoded'", ) from exc return cls( data, event=headers["x-github-event"], delivery_id=headers["x-github-delivery"], )
Example #26
Source File: __init__.py From gidgethub with Apache License 2.0 | 5 votes |
def __init__(self, response: Any) -> None: super().__init__(http.HTTPStatus(401), response)
Example #27
Source File: __init__.py From gidgethub with Apache License 2.0 | 5 votes |
def __init__(self, errors: Any, *args: Any) -> None: """Store the error details.""" self.errors = errors super().__init__(http.HTTPStatus.UNPROCESSABLE_ENTITY, *args)
Example #28
Source File: __init__.py From gidgethub with Apache License 2.0 | 5 votes |
def __init__(self, errors: Any, *args: Any) -> None: """Store the error details.""" self.errors = errors super().__init__(http.HTTPStatus.UNPROCESSABLE_ENTITY, *args)
Example #29
Source File: __init__.py From gidgethub with Apache License 2.0 | 5 votes |
def __init__(self, rate_limit: Any, *args: Any) -> None: self.rate_limit = rate_limit if not args: super().__init__(http.HTTPStatus.FORBIDDEN, "rate limit exceeded") else: super().__init__(http.HTTPStatus.FORBIDDEN, *args)
Example #30
Source File: __init__.py From gidgethub with Apache License 2.0 | 5 votes |
def __init__(self, response: str) -> None: self.response = response super().__init__(http.HTTPStatus.UNPROCESSABLE_ENTITY)