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


Python http_client.UNAUTHORIZED属性代码示例

本文整理汇总了Python中six.moves.http_client.UNAUTHORIZED属性的典型用法代码示例。如果您正苦于以下问题:Python http_client.UNAUTHORIZED属性的具体用法?Python http_client.UNAUTHORIZED怎么用?Python http_client.UNAUTHORIZED使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在six.moves.http_client的用法示例。


在下文中一共展示了http_client.UNAUTHORIZED属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_request_refresh

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_request_refresh(self):
        credentials = mock.Mock(wraps=CredentialsStub())
        final_response = make_response(status=http_client.OK)
        # First request will 401, second request will succeed.
        adapter = AdapterStub(
            [make_response(status=http_client.UNAUTHORIZED), final_response]
        )

        authed_session = google.auth.transport.requests.AuthorizedSession(
            credentials, refresh_timeout=60
        )
        authed_session.mount(self.TEST_URL, adapter)

        result = authed_session.request("GET", self.TEST_URL)

        assert result == final_response
        assert credentials.before_request.call_count == 2
        assert credentials.refresh.called
        assert len(adapter.requests) == 2

        assert adapter.requests[0].url == self.TEST_URL
        assert adapter.requests[0].headers["authorization"] == "token"

        assert adapter.requests[1].url == self.TEST_URL
        assert adapter.requests[1].headers["authorization"] == "token1" 
开发者ID:googleapis,项目名称:google-auth-library-python,代码行数:27,代码来源:test_requests.py

示例2: test_request_max_allowed_time_w_transport_timeout_no_error

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_request_max_allowed_time_w_transport_timeout_no_error(self, frozen_time):
        tick_one_second = functools.partial(
            frozen_time.tick, delta=datetime.timedelta(seconds=1.0)
        )

        credentials = mock.Mock(
            wraps=TimeTickCredentialsStub(time_tick=tick_one_second)
        )
        adapter = TimeTickAdapterStub(
            time_tick=tick_one_second,
            responses=[
                make_response(status=http_client.UNAUTHORIZED),
                make_response(status=http_client.OK),
            ],
        )

        authed_session = google.auth.transport.requests.AuthorizedSession(credentials)
        authed_session.mount(self.TEST_URL, adapter)

        # A short configured transport timeout does not affect max_allowed_time.
        # The latter is not adjusted to it and is only concerned with the actual
        # execution time. The call below should thus not raise a timeout error.
        authed_session.request("GET", self.TEST_URL, timeout=0.5, max_allowed_time=3.1) 
开发者ID:googleapis,项目名称:google-auth-library-python,代码行数:25,代码来源:test_requests.py

示例3: test_urlopen_refresh

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_urlopen_refresh(self):
        credentials = mock.Mock(wraps=CredentialsStub())
        final_response = ResponseStub(status=http_client.OK)
        # First request will 401, second request will succeed.
        http = HttpStub([ResponseStub(status=http_client.UNAUTHORIZED), final_response])

        authed_http = google.auth.transport.urllib3.AuthorizedHttp(
            credentials, http=http
        )

        authed_http = authed_http.urlopen("GET", "http://example.com")

        assert authed_http == final_response
        assert credentials.before_request.call_count == 2
        assert credentials.refresh.called
        assert http.requests == [
            ("GET", self.TEST_URL, None, {"authorization": "token"}, {}),
            ("GET", self.TEST_URL, None, {"authorization": "token1"}, {}),
        ] 
开发者ID:googleapis,项目名称:google-auth-library-python,代码行数:21,代码来源:test_urllib3.py

示例4: test_refresh_failure_unauthorzed

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_refresh_failure_unauthorzed(self, mock_donor_credentials):
        credentials = self.make_credentials(lifetime=None)

        response_body = {
            "error": {
                "code": 403,
                "message": "The caller does not have permission",
                "status": "PERMISSION_DENIED",
            }
        }

        request = self.make_request(
            data=json.dumps(response_body), status=http_client.UNAUTHORIZED
        )

        with pytest.raises(exceptions.RefreshError) as excinfo:
            credentials.refresh(request)

        assert excinfo.match(impersonated_credentials._REFRESH_ERROR)

        assert not credentials.valid
        assert credentials.expired 
开发者ID:googleapis,项目名称:google-auth-library-python,代码行数:24,代码来源:test_impersonated_credentials.py

示例5: get_resource_by_pk

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def get_resource_by_pk(self, pk, **kwargs):
        """
        Retrieve resource by a primary key.
        """
        try:
            instance = self.manager.get_by_id(pk, **kwargs)
        except Exception as e:
            traceback.print_exc()
            # Hack for "Unauthorized" exceptions, we do want to propagate those
            response = getattr(e, 'response', None)
            status_code = getattr(response, 'status_code', None)
            if status_code and status_code == http_client.UNAUTHORIZED:
                raise e

            instance = None

        return instance 
开发者ID:StackStorm,项目名称:st2,代码行数:19,代码来源:resource.py

示例6: __init__

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def __init__(self, request, retryable_codes, service, method_config):
            """Initialize an individual API request.

            Args:
              request: An http_wrapper.Request object.
              retryable_codes: A list of integer HTTP codes that can
                  be retried.
              service: A service inheriting from base_api.BaseApiService.
              method_config: Method config for the desired API request.

            """
            self.__retryable_codes = list(
                set(retryable_codes + [http_client.UNAUTHORIZED]))
            self.__http_response = None
            self.__service = service
            self.__method_config = method_config

            self.http_request = request
            # TODO(user): Add some validation to these fields.
            self.__response = None
            self.__exception = None 
开发者ID:google,项目名称:apitools,代码行数:23,代码来源:batch.py

示例7: _handle_error

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def _handle_error(url, response):
    """Handle response status codes."""
    handlers = {
        http_client.NOT_FOUND: NotFoundError(
            'Resource not found: {}'.format(url)
        ),
        # XXX: Correct code is CONFLICT. Support invalid FOUND during
        #      migration.
        http_client.FOUND: AlreadyExistsError(
            'Resource already exists: {}'.format(url)
        ),
        http_client.CONFLICT: AlreadyExistsError(
            'Resource already exists: {}'.format(url)
        ),
        http_client.TOO_MANY_REQUESTS: TooManyRequestsError(response),
        http_client.FAILED_DEPENDENCY: ValidationError(response),
        # XXX: Correct code is FORBIDDEN. Support invalid UNAUTHORIZED during
        #      migration.
        http_client.UNAUTHORIZED: NotAuthorizedError(response),
        http_client.FORBIDDEN: NotAuthorizedError(response),
        http_client.BAD_REQUEST: BadRequestError(response),
    }

    if response.status_code in handlers:
        raise handlers[response.status_code] 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:27,代码来源:restclient.py

示例8: test_request_max_allowed_time_w_refresh_timeout_no_error

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_request_max_allowed_time_w_refresh_timeout_no_error(self, frozen_time):
        tick_one_second = functools.partial(
            frozen_time.tick, delta=datetime.timedelta(seconds=1.0)
        )

        credentials = mock.Mock(
            wraps=TimeTickCredentialsStub(time_tick=tick_one_second)
        )
        adapter = TimeTickAdapterStub(
            time_tick=tick_one_second,
            responses=[
                make_response(status=http_client.UNAUTHORIZED),
                make_response(status=http_client.OK),
            ],
        )

        authed_session = google.auth.transport.requests.AuthorizedSession(
            credentials, refresh_timeout=1.1
        )
        authed_session.mount(self.TEST_URL, adapter)

        # A short configured refresh timeout does not affect max_allowed_time.
        # The latter is not adjusted to it and is only concerned with the actual
        # execution time. The call below should thus not raise a timeout error
        # (and `timeout` does not come into play either, as it's very long).
        authed_session.request("GET", self.TEST_URL, timeout=60, max_allowed_time=3.1) 
开发者ID:googleapis,项目名称:google-auth-library-python,代码行数:28,代码来源:test_requests.py

示例9: test_request_timeout_w_refresh_timeout_timeout_error

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_request_timeout_w_refresh_timeout_timeout_error(self, frozen_time):
        tick_one_second = functools.partial(
            frozen_time.tick, delta=datetime.timedelta(seconds=1.0)
        )

        credentials = mock.Mock(
            wraps=TimeTickCredentialsStub(time_tick=tick_one_second)
        )
        adapter = TimeTickAdapterStub(
            time_tick=tick_one_second,
            responses=[
                make_response(status=http_client.UNAUTHORIZED),
                make_response(status=http_client.OK),
            ],
        )

        authed_session = google.auth.transport.requests.AuthorizedSession(
            credentials, refresh_timeout=100
        )
        authed_session.mount(self.TEST_URL, adapter)

        # An UNAUTHORIZED response triggers a refresh (an extra request), thus
        # the final request that otherwise succeeds results in a timeout error
        # (all three requests together last 3 mocked seconds).
        with pytest.raises(requests.exceptions.Timeout):
            authed_session.request(
                "GET", self.TEST_URL, timeout=60, max_allowed_time=2.9
            ) 
开发者ID:googleapis,项目名称:google-auth-library-python,代码行数:30,代码来源:test_requests.py

示例10: test_no_user_or_user_id

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_no_user_or_user_id(self):
        response = self.request.get_response(self.middleware)
        self.assertEqual(response.status_int, http.UNAUTHORIZED) 
开发者ID:openstack,项目名称:masakari,代码行数:5,代码来源:test_auth.py

示例11: _unauthorized

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def _unauthorized(self, message):
        body = {'error': {
            'code': httplib.UNAUTHORIZED,
            'title': httplib.responses.get(httplib.UNAUTHORIZED),
            'message': message,
        }}

        raise exc.HTTPUnauthorized(body=jsonutils.dumps(body),
                                   headers=self.reject_auth_headers,
                                   charset='UTF-8',
                                   content_type='application/json') 
开发者ID:openstack,项目名称:vitrage,代码行数:13,代码来源:basic_and_keystone_auth.py

示例12: test_basic_mode_auth_wrong_authorization

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_basic_mode_auth_wrong_authorization(self, *args):
        wrong_headers = HEADERS.copy()
        wrong_headers['Authorization'] = 'Basic dml0cmFnZTpwdml0cmFnZT=='
        resp = self.post_json('/event',
                              params={
                                  'time': datetime.now().isoformat(),
                                  'type': EVENT_TYPE,
                                  'details': EVENT_DETAILS
                              },
                              headers=wrong_headers,
                              expect_errors=True)
        self.assertEqual(httplib.UNAUTHORIZED, resp.status_code)
        self.assertDictEqual(ERR_MISSING_VERSIONED_IDENTITY_ENDPOINTS,
                             resp.json) 
开发者ID:openstack,项目名称:vitrage,代码行数:16,代码来源:test_basic.py

示例13: test_in_basic_mode_auth_no_header

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_in_basic_mode_auth_no_header(self):
        resp = self.post_json('/event', expect_errors=True)

        self.assertEqual(httplib.UNAUTHORIZED, resp.status_code)
        self.assertDictEqual(ERR_MISSING_AUTH, resp.json) 
开发者ID:openstack,项目名称:vitrage,代码行数:7,代码来源:test_basic.py

示例14: abort_request

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def abort_request(status_code=http_client.UNAUTHORIZED, message='Invalid or missing credentials'):
    return abort(status_code, message) 
开发者ID:StackStorm,项目名称:st2,代码行数:4,代码来源:handlers.py

示例15: test_st2auth

# 需要导入模块: from six.moves import http_client [as 别名]
# 或者: from six.moves.http_client import UNAUTHORIZED [as 别名]
def test_st2auth(self):
        port = random.randint(10000, 30000)
        cmd = ('gunicorn st2auth.wsgi:application -k eventlet -b "127.0.0.1:%s" --workers 1' % port)
        env = os.environ.copy()
        env['ST2_CONFIG_PATH'] = ST2_CONFIG_PATH
        process = subprocess.Popen(cmd, env=env, shell=True, preexec_fn=os.setsid)
        try:
            self.add_process(process=process)
            eventlet.sleep(8)
            self.assertProcessIsRunning(process=process)
            response = requests.post('http://127.0.0.1:%s/tokens' % (port))
            self.assertEqual(response.status_code, http_client.UNAUTHORIZED)
        finally:
            kill_process(process) 
开发者ID:StackStorm,项目名称:st2,代码行数:16,代码来源:test_gunicorn_configs.py


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