Python six.moves.http_client.OK Examples

The following are 30 code examples of six.moves.http_client.OK(). 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 six.moves.http_client , or try the search function .
Example #1
Source File: iam.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def _make_signing_request(self, message):
        """Makes a request to the API signBlob API."""
        message = _helpers.to_bytes(message)

        method = "POST"
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps(
            {"payload": base64.b64encode(message).decode("utf-8")}
        ).encode("utf-8")

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                "Error calling the IAM signBytes API: {}".format(response.data)
            )

        return json.loads(response.data.decode("utf-8")) 
Example #2
Source File: test__upload.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def test__process_response_success(self):
        upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
        _fix_up_virtual(upload)

        # Check / set status before.
        assert upload._bytes_uploaded == 0
        upload._bytes_uploaded = 20
        assert not upload._finished

        # Set the response body.
        bytes_sent = 158
        total_bytes = upload._bytes_uploaded + bytes_sent
        response_body = u'{{"size": "{:d}"}}'.format(total_bytes)
        response_body = response_body.encode(u"utf-8")
        response = mock.Mock(
            content=response_body,
            status_code=http_client.OK,
            spec=["content", "status_code"],
        )
        ret_val = upload._process_response(response, bytes_sent)
        assert ret_val is None
        # Check status after.
        assert upload._bytes_uploaded == total_bytes
        assert upload._finished 
Example #3
Source File: test__upload.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def test__process_response_bad_status(self):
        upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
        _fix_up_virtual(upload)

        # Make sure the upload is valid before the failure.
        assert not upload.invalid
        response = _make_response(status_code=http_client.NOT_FOUND)
        with pytest.raises(common.InvalidResponse) as exc_info:
            upload._process_response(response, None)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 5
        assert error.args[1] == response.status_code
        assert error.args[3] == http_client.OK
        assert error.args[4] == resumable_media.PERMANENT_REDIRECT
        # Make sure the upload is invalid after the failure.
        assert upload.invalid 
Example #4
Source File: test_download.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def secret_file(authorized_transport, bucket):
    blob_name = u"super-seekrit.txt"
    data = b"Please do not tell anyone my encrypted seekrit."

    upload_url = utils.SIMPLE_UPLOAD_TEMPLATE.format(blob_name=blob_name)
    headers = utils.get_encryption_headers()
    upload = resumable_requests.SimpleUpload(upload_url, headers=headers)
    response = upload.transmit(authorized_transport, data, PLAIN_TEXT)
    assert response.status_code == http_client.OK

    yield blob_name, data, headers

    delete_blob(authorized_transport, blob_name)


# Transport that returns corrupt data, so we can exercise checksum handling. 
Example #5
Source File: test_run.py    From column with GNU General Public License v3.0 6 votes vote down vote up
def _test_get_run_by_id(self):
        response = self.app.get('/runs/1234')
        self.assertEqual(http_client.NOT_FOUND, response.status_code)

        pb = 'tests/fixtures/playbooks/hello_world.yml'
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(playbook_path=pb,
                                 inventory_file='localhosti,',
                                 options={'connection': 'local'})),
            content_type='application/json')
        res_dict = json.loads(response.data)
        run_id = res_dict['id']
        self.assertEqual(http_client.CREATED, response.status_code)
        response = self.app.get('/runs/{}'.format(run_id))
        self.assertEqual(http_client.OK, response.status_code)
        self._wait_for_run_complete(run_id) 
Example #6
Source File: test_download.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def _mock_raw_response(status_code=http_client.OK, chunks=(), headers=None):
    if headers is None:
        headers = {}

    mock_raw = mock.Mock(headers=headers, spec=["stream"])
    mock_raw.stream.return_value = iter(chunks)
    response = mock.MagicMock(
        headers=headers,
        status_code=int(status_code),
        raw=mock_raw,
        spec=[
            u"__enter__",
            u"__exit__",
            u"iter_content",
            u"status_code",
            u"headers",
            u"raw",
        ],
    )
    # i.e. context manager returns ``self``.
    response.__enter__.return_value = response
    response.__exit__.return_value = None
    return response 
Example #7
Source File: controllers.py    From devicehive-video-analysis with Apache License 2.0 6 votes vote down vote up
def get(self, handler, *args, **kwargs):
        handler.send_response(http_client.OK)
        c_type = 'multipart/x-mixed-replace; boundary=--mjpegboundary'
        handler.send_header('Content-Type', c_type)
        handler.end_headers()
        prev = None
        while handler.server.server.is_running:
            data, frame_id = handler.server.server.get_frame()
            if data is not None and frame_id != prev:
                prev = frame_id
                handler.wfile.write(b'--mjpegboundary\r\n')
                handler.send_header('Content-type', 'image/jpeg')
                handler.send_header('Content-length', str(len(data)))
                handler.end_headers()
                handler.wfile.write(data)
            else:
                time.sleep(0.025) 
Example #8
Source File: annotator.py    From python-stanford-corenlp with MIT License 6 votes vote down vote up
def do_GET(self):
            """
            Handle a ping request
            """
            if not self.path.endswith("/"): self.path += "/"
            if self.path == "/ping/":
                msg = "pong".encode("UTF-8")

                self.send_response(HTTPStatus.OK)
                self.send_header("Content-Type", "text/application")
                self.send_header("Content-Length", len(msg))
                self.end_headers()
                self.wfile.write(msg)
            else:
                self.send_response(HTTPStatus.BAD_REQUEST)
                self.end_headers() 
Example #9
Source File: test__upload.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def test__process_response_bad_status(self):
        upload = _upload.UploadBase(SIMPLE_URL)
        _fix_up_virtual(upload)

        # Make sure **not finished** before.
        assert not upload.finished
        status_code = http_client.SERVICE_UNAVAILABLE
        response = _make_response(status_code=status_code)
        with pytest.raises(common.InvalidResponse) as exc_info:
            upload._process_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 4
        assert error.args[1] == status_code
        assert error.args[3] == http_client.OK
        # Make sure **finished** after (even in failure).
        assert upload.finished 
Example #10
Source File: betfair.py    From betfair.py with MIT License 6 votes vote down vote up
def login(self, username, password):
        """Log in to Betfair. Sets `session_token` if successful.

        :param str username: Username
        :param str password: Password
        :raises: BetfairLoginError
        """
        response = self.session.post(
            os.path.join(self.identity_url, 'certlogin'),
            cert=self.cert_file,
            data=urllib.urlencode({
                'username': username,
                'password': password,
            }),
            headers={
                'X-Application': self.app_key,
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            timeout=self.timeout,
        )
        utils.check_status_code(response, [httplib.OK])
        data = response.json()
        if data.get('loginStatus') != 'SUCCESS':
            raise exceptions.LoginError(response, data)
        self.session_token = data['sessionToken'] 
Example #11
Source File: test__download.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def test__process_response_bad_status(self):
        download = _download.Download(EXAMPLE_URL)
        _fix_up_virtual(download)

        # Make sure **not finished** before.
        assert not download.finished
        response = mock.Mock(
            status_code=int(http_client.NOT_FOUND), spec=["status_code"]
        )
        with pytest.raises(common.InvalidResponse) as exc_info:
            download._process_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 5
        assert error.args[1] == response.status_code
        assert error.args[3] == http_client.OK
        assert error.args[4] == http_client.PARTIAL_CONTENT
        # Make sure **finished** even after a failure.
        assert download.finished 
Example #12
Source File: test_requests.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test_request_max_allowed_time_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.OK)]
        )

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

        # Because a request takes a full mocked second, max_allowed_time shorter
        # than that will cause a timeout error.
        with pytest.raises(requests.exceptions.Timeout):
            authed_session.request("GET", self.TEST_URL, max_allowed_time=0.9) 
Example #13
Source File: controllers.py    From devicehive-audio-analysis with Apache License 2.0 6 votes vote down vote up
def get(self, handler, *args, **kwargs):
        f = StringIO()
        for timestamp, predictions in handler.server.server.events_queue:
            data = {
                'timestamp': '{:%Y-%m-%d %H:%M:%S}'.format(timestamp),
                'predictions': predictions
            }
            f.writelines(self.render_template('event.html', **data))

        response = f.getvalue()
        f.close()

        handler.send_response(http_client.OK)
        handler.send_header('Content-type', 'text/html')
        handler.end_headers()
        handler.wfile.write(response.encode()) 
Example #14
Source File: id_token.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def _fetch_certs(request, certs_url):
    """Fetches certificates.

    Google-style cerificate endpoints return JSON in the format of
    ``{'key id': 'x509 certificate'}``.

    Args:
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        certs_url (str): The certificate endpoint URL.

    Returns:
        Mapping[str, str]: A mapping of public key ID to x.509 certificate
            data.
    """
    response = request(certs_url, method="GET")

    if response.status != http_client.OK:
        raise exceptions.TransportError(
            "Could not fetch certificates at {}".format(certs_url)
        )

    return json.loads(response.data.decode("utf-8")) 
Example #15
Source File: tools.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def do_GET(self):
        """Handle a GET request.

        Parses the query parameters and prints a message
        if the flow has completed. Note that we can't detect
        if an error occurred.
        """
        self.send_response(http_client.OK)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        query = self.path.split('?', 1)[-1]
        query = dict(urllib.parse.parse_qsl(query))
        self.server.query_params = query
        self.wfile.write(
            b"<html><head><title>Authentication Status</title></head>")
        self.wfile.write(
            b"<body><p>The authentication flow has completed.</p>")
        self.wfile.write(b"</body></html>") 
Example #16
Source File: test_impersonated_credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test_sign_bytes(self, mock_donor_credentials, mock_authorizedsession_sign):
        credentials = self.make_credentials(lifetime=None)
        token = "token"

        expire_time = (
            _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
        ).isoformat("T") + "Z"
        token_response_body = {"accessToken": token, "expireTime": expire_time}

        response = mock.create_autospec(transport.Response, instance=False)
        response.status = http_client.OK
        response.data = _helpers.to_bytes(json.dumps(token_response_body))

        request = mock.create_autospec(transport.Request, instance=False)
        request.return_value = response

        credentials.refresh(request)

        assert credentials.valid
        assert not credentials.expired

        signature = credentials.sign_bytes(b"signed bytes")
        assert signature == b"signature" 
Example #17
Source File: test_impersonated_credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test_refresh_failure_malformed_expire_time(self, mock_donor_credentials):
        credentials = self.make_credentials(lifetime=None)
        token = "token"

        expire_time = (_helpers.utcnow() + datetime.timedelta(seconds=500)).isoformat(
            "T"
        )
        response_body = {"accessToken": token, "expireTime": expire_time}

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

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

        assert excinfo.match(impersonated_credentials._REFRESH_ERROR)

        assert not credentials.valid
        assert credentials.expired 
Example #18
Source File: test_impersonated_credentials.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def make_request(
        self,
        data,
        status=http_client.OK,
        headers=None,
        side_effect=None,
        use_data_bytes=True,
    ):
        response = mock.create_autospec(transport.Response, instance=False)
        response.status = status
        response.data = _helpers.to_bytes(data) if use_data_bytes else data
        response.headers = headers or {}

        request = mock.create_autospec(transport.Request, instance=False)
        request.side_effect = side_effect
        request.return_value = response

        return request 
Example #19
Source File: gce.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _get_service_account_email(http_request=None):
    """Get the GCE service account email from the current environment.

    Args:
        http_request: callable, (Optional) a callable that matches the method
                      signature of httplib2.Http.request, used to make
                      the request to the metadata service.

    Returns:
        tuple, A pair where the first entry is an optional response (from a
        failed request) and the second is service account email found (as
        a string).
    """
    if http_request is None:
        http_request = httplib2.Http().request
    response, content = http_request(
        _DEFAULT_EMAIL_METADATA, headers={'Metadata-Flavor': 'Google'})
    if response.status == http_client.OK:
        content = _from_bytes(content)
        return None, content
    else:
        return response, content 
Example #20
Source File: test_urllib3.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
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"}, {}),
        ] 
Example #21
Source File: test_requests.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
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) 
Example #22
Source File: test_requests.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
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" 
Example #23
Source File: gce.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _refresh(self, http_request):
        """Refreshes the access_token.

        Skip all the storage hoops and just refresh using the API.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make
                          the refresh request.

        Raises:
            HttpAccessTokenRefreshError: When the refresh fails.
        """
        response, content = http_request(
            META, headers={'Metadata-Flavor': 'Google'})
        content = _from_bytes(content)
        if response.status == http_client.OK:
            try:
                token_content = json.loads(content)
            except Exception as e:
                raise HttpAccessTokenRefreshError(str(e),
                                                  status=response.status)
            self.access_token = token_content['access_token']
        else:
            if response.status == http_client.NOT_FOUND:
                content += (' This can occur if a VM was created'
                            ' with no service account or scopes.')
            raise HttpAccessTokenRefreshError(content, status=response.status) 
Example #24
Source File: test__upload.py    From google-resumable-media-python with Apache License 2.0 5 votes vote down vote up
def _make_response(status_code=http_client.OK, headers=None):
    headers = headers or {}
    return mock.Mock(
        headers=headers, status_code=status_code, spec=["headers", "status_code"]
    ) 
Example #25
Source File: _metadata.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get(http, path, root=METADATA_ROOT, recursive=None):
    """Fetch a resource from the metadata server.

    Args:
        http: an object to be used to make HTTP requests.
        path: A string indicating the resource to retrieve. For example,
            'instance/service-accounts/default'
        root: A string indicating the full path to the metadata server root.
        recursive: A boolean indicating whether to do a recursive query of
            metadata. See
            https://cloud.google.com/compute/docs/metadata#aggcontents

    Returns:
        A dictionary if the metadata server returns JSON, otherwise a string.

    Raises:
        http_client.HTTPException if an error corrured while
        retrieving metadata.
    """
    url = urlparse.urljoin(root, path)
    url = _helpers._add_query_parameter(url, 'recursive', recursive)

    response, content = transport.request(
        http, url, headers=METADATA_HEADERS)

    if response.status == http_client.OK:
        decoded = _helpers._from_bytes(content)
        if response['content-type'] == 'application/json':
            return json.loads(decoded)
        else:
            return decoded
    else:
        raise http_client.HTTPException(
            'Failed to retrieve {0} from the Google Compute Engine'
            'metadata service. Response:\n{1}'.format(url, response)) 
Example #26
Source File: client.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _do_revoke(self, http_request, token):
        """Revokes this credential and deletes the stored copy (if it exists).

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make the
                          refresh request.
            token: A string used as the token to be revoked. Can be either an
                   access_token or refresh_token.

        Raises:
            TokenRevokeError: If the revoke request does not return with a
                              200 OK.
        """
        logger.info('Revoking token')
        query_params = {'token': token}
        token_revoke_uri = _update_query_params(self.revoke_uri, query_params)
        resp, content = http_request(token_revoke_uri)
        if resp.status == http_client.OK:
            self.invalid = True
        else:
            error_msg = 'Invalid response %s.' % resp.status
            try:
                d = json.loads(_from_bytes(content))
                if 'error' in d:
                    error_msg = d['error']
            except (TypeError, ValueError):
                pass
            raise TokenRevokeError(error_msg)

        if self.store:
            self.store.delete() 
Example #27
Source File: test_download.py    From google-resumable-media-python with Apache License 2.0 5 votes vote down vote up
def _mock_transport(self, start, chunk_size, total_bytes, content=b""):
        transport = mock.Mock(spec=["request"])
        assert len(content) == chunk_size
        transport.request.return_value = self._mock_response(
            start,
            start + chunk_size - 1,
            total_bytes,
            content=content,
            status_code=int(http_client.OK),
        )

        return transport 
Example #28
Source File: controllers.py    From devicehive-audio-analysis with Apache License 2.0 5 votes vote down vote up
def get(self, handler, *args, **kwargs):
        response = self.render_template('events.html')

        handler.send_response(http_client.OK)
        handler.send_header('Content-type', 'text/html')
        handler.end_headers()
        handler.wfile.write(response.encode()) 
Example #29
Source File: client.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _detect_gce_environment():
    """Determine if the current environment is Compute Engine.

    Returns:
        Boolean indicating whether or not the current environment is Google
        Compute Engine.
    """
    # NOTE: The explicit ``timeout`` is a workaround. The underlying
    #       issue is that resolving an unknown host on some networks will take
    #       20-30 seconds; making this timeout short fixes the issue, but
    #       could lead to false negatives in the event that we are on GCE, but
    #       the metadata resolution was particularly slow. The latter case is
    #       "unlikely".
    connection = six.moves.http_client.HTTPConnection(
        _GCE_METADATA_HOST, timeout=1)

    try:
        headers = {_METADATA_FLAVOR_HEADER: _DESIRED_METADATA_FLAVOR}
        connection.request('GET', '/', headers=headers)
        response = connection.getresponse()
        if response.status == http_client.OK:
            return (response.getheader(_METADATA_FLAVOR_HEADER) ==
                    _DESIRED_METADATA_FLAVOR)
    except socket.error:  # socket.timeout or socket.error(64, 'Host is down')
        logger.info('Timeout attempting to reach GCE metadata service.')
        return False
    finally:
        connection.close() 
Example #30
Source File: client.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _do_retrieve_scopes(self, http_request, token):
        """Retrieves the list of authorized scopes from the OAuth2 provider.

        Args:
            http_request: callable, a callable that matches the method
                          signature of httplib2.Http.request, used to make the
                          refresh request.
            token: A string used as the token to identify the credentials to
                   the provider.

        Raises:
            Error: When refresh fails, indicating the the access token is
                   invalid.
        """
        logger.info('Refreshing scopes')
        query_params = {'access_token': token, 'fields': 'scope'}
        token_info_uri = _update_query_params(self.token_info_uri,
                                              query_params)
        resp, content = http_request(token_info_uri)
        content = _from_bytes(content)
        if resp.status == http_client.OK:
            d = json.loads(content)
            self.scopes = set(util.string_to_scopes(d.get('scope', '')))
        else:
            error_msg = 'Invalid response %s.' % (resp.status,)
            try:
                d = json.loads(content)
                if 'error_description' in d:
                    error_msg = d['error_description']
            except (TypeError, ValueError):
                pass
            raise Error(error_msg)