本文整理匯總了Python中http.HTTPStatus方法的典型用法代碼示例。如果您正苦於以下問題:Python http.HTTPStatus方法的具體用法?Python http.HTTPStatus怎麽用?Python http.HTTPStatus使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類http
的用法示例。
在下文中一共展示了http.HTTPStatus方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _register_responses
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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)
示例2: test_api_registers_error_responses
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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')
}
}
}
示例3: test_blueprint_arguments_documents_error_response
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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)
)
示例4: test_blueprint_response_description
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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'
示例5: _do_req
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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()
示例6: test_http_status_enum
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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)
)
示例7: name_of
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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)}'
示例8: __init__
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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
示例9: _is_token_expired
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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
示例10: test_422_custom_code
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
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.'"
)
示例11: on_headers_complete
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
def on_headers_complete(self):
self.response.status = HTTPStatus(self.http_parser.get_status_code())
示例12: _prepare_etag_doc
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
def _prepare_etag_doc(self, doc, doc_info, app, method, **kwargs):
if (
doc_info.get('etag', False) and
not app.config.get('ETAG_DISABLED', False)
):
responses = {}
method_u = method.upper()
if method_u in self.METHODS_CHECKING_NOT_MODIFIED:
responses[304] = http.HTTPStatus(304).name
if method_u in self.METHODS_NEEDING_CHECK_ETAG:
responses[412] = http.HTTPStatus(412).name
responses[428] = http.HTTPStatus(428).name
if responses:
doc = deepupdate(doc, {'responses': responses})
return doc
示例13: __init__
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
def __init__(self, status: HTTPStatus, *args, **kwargs):
self._status = status
super().__init__(*args, **kwargs)
示例14: status
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
def status(self) -> HTTPStatus:
return self._status
示例15: _to_status_code
# 需要導入模塊: import http [as 別名]
# 或者: from http import HTTPStatus [as 別名]
def _to_status_code(response_status):
if isinstance(response_status, HTTPStatus):
return response_status.value
else:
return response_status