当前位置: 首页>>代码示例>>Python>>正文


Python http.HTTPStatus方法代码示例

本文整理汇总了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) 
开发者ID:marshmallow-code,项目名称:flask-smorest,代码行数:21,代码来源:__init__.py

示例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')
                        }
                    }
                } 
开发者ID:marshmallow-code,项目名称:flask-smorest,代码行数:23,代码来源:test_api.py

示例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)
        ) 
开发者ID:marshmallow-code,项目名称:flask-smorest,代码行数:26,代码来源:test_blueprint.py

示例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' 
开发者ID:marshmallow-code,项目名称:flask-smorest,代码行数:25,代码来源:test_blueprint.py

示例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() 
开发者ID:wasp,项目名称:eureka,代码行数:22,代码来源:client.py

示例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)
        ) 
开发者ID:rycus86,项目名称:prometheus_flask_exporter,代码行数:26,代码来源:test_endpoint.py

示例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)}' 
开发者ID:anyant,项目名称:rssant,代码行数:23,代码来源:response.py

示例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 
开发者ID:anyant,项目名称:rssant,代码行数:23,代码来源:response.py

示例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 
开发者ID:cloudfoundry-community,项目名称:cf-python-client,代码行数:23,代码来源:client.py

示例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.'"
        ) 
开发者ID:brettcannon,项目名称:gidgethub,代码行数:21,代码来源:test_sansio.py

示例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()) 
开发者ID:wasp,项目名称:waspy,代码行数:4,代码来源:httptransport.py

示例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 
开发者ID:marshmallow-code,项目名称:flask-smorest,代码行数:17,代码来源:etag.py

示例13: __init__

# 需要导入模块: import http [as 别名]
# 或者: from http import HTTPStatus [as 别名]
def __init__(self, status: HTTPStatus, *args, **kwargs):
        self._status = status
        super().__init__(*args, **kwargs) 
开发者ID:wasp,项目名称:eureka,代码行数:5,代码来源:exc.py

示例14: status

# 需要导入模块: import http [as 别名]
# 或者: from http import HTTPStatus [as 别名]
def status(self) -> HTTPStatus:
        return self._status 
开发者ID:wasp,项目名称:eureka,代码行数:4,代码来源:exc.py

示例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 
开发者ID:rycus86,项目名称:prometheus_flask_exporter,代码行数:7,代码来源:__init__.py


注:本文中的http.HTTPStatus方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。