Python http.client.OK Examples

The following are 30 code examples of 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 http.client , or try the search function .
Example #1
Source File: http.py    From scroll-phat-hd with MIT License 6 votes vote down vote up
def flip():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("flip", (bool(data["x"]), bool(data["y"]))))
    except TypeError:
        response = {"result": "TypeError", "error": "Could not cast data correctly. Both `x` and `y` must be set to true or false."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except KeyError:
        response = {"result": "KeyError", "error": "Could not cast data correctly. Both `x` and `y` must be in the posted json data."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
Example #2
Source File: test_httplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_chunked_head(self):
        chunked_start = (
            'HTTP/1.1 200 OK\r\n'
            'Transfer-Encoding: chunked\r\n\r\n'
            'a\r\n'
            'hello world\r\n'
            '1\r\n'
            'd\r\n'
        )
        sock = FakeSocket(chunked_start + last_chunk + chunked_end)
        resp = client.HTTPResponse(sock, method="HEAD")
        resp.begin()
        self.assertEqual(resp.read(), b'')
        self.assertEqual(resp.status, 200)
        self.assertEqual(resp.reason, 'OK')
        self.assertTrue(resp.isclosed())
        self.assertFalse(resp.closed)
        resp.close()
        self.assertTrue(resp.closed) 
Example #3
Source File: test_httplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_readinto_chunked_head(self):
        chunked_start = (
            'HTTP/1.1 200 OK\r\n'
            'Transfer-Encoding: chunked\r\n\r\n'
            'a\r\n'
            'hello world\r\n'
            '1\r\n'
            'd\r\n'
        )
        sock = FakeSocket(chunked_start + last_chunk + chunked_end)
        resp = client.HTTPResponse(sock, method="HEAD")
        resp.begin()
        b = bytearray(5)
        n = resp.readinto(b)
        self.assertEqual(n, 0)
        self.assertEqual(bytes(b), b'\x00'*5)
        self.assertEqual(resp.status, 200)
        self.assertEqual(resp.reason, 'OK')
        self.assertTrue(resp.isclosed())
        self.assertFalse(resp.closed)
        resp.close()
        self.assertTrue(resp.closed) 
Example #4
Source File: test_httplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_response_headers(self):
        # test response with multiple message headers with the same field name.
        text = ('HTTP/1.1 200 OK\r\n'
                'Set-Cookie: Customer="WILE_E_COYOTE"; '
                'Version="1"; Path="/acme"\r\n'
                'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
                ' Path="/acme"\r\n'
                '\r\n'
                'No body\r\n')
        hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
               ', '
               'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
        s = FakeSocket(text)
        r = client.HTTPResponse(s)
        r.begin()
        cookies = r.getheader("Set-Cookie")
        self.assertEqual(cookies, hdr) 
Example #5
Source File: auth.py    From flytekit with Apache License 2.0 6 votes vote down vote up
def request_access_token(self, auth_code):
        if self._state != auth_code.state:
            raise ValueError("Unexpected state parameter [{}] passed".format(auth_code.state))
        self._params.update({
            "code": auth_code.code,
            "code_verifier": self._code_verifier,
            "grant_type": "authorization_code",
        })
        resp = _requests.post(
            url=self._token_endpoint,
            data=self._params,
            headers=self._headers,
            allow_redirects=False
        )
        if resp.status_code != _StatusCodes.OK:
            # TODO: handle expected (?) error cases:
            #  https://auth0.com/docs/flows/guides/device-auth/call-api-device-auth#token-responses
            raise Exception('Failed to request access token with response: [{}] {}'.format(
                resp.status_code, resp.content))
        self._initialize_credentials(resp) 
Example #6
Source File: auth.py    From flytekit with Apache License 2.0 6 votes vote down vote up
def refresh_access_token(self):
        if self._refresh_token is None:
            raise ValueError("no refresh token available with which to refresh authorization credentials")

        resp = _requests.post(
            url=self._token_endpoint,
            data={'grant_type': 'refresh_token',
                  'client_id': self._client_id,
                  'refresh_token': self._refresh_token},
            headers=self._headers,
            allow_redirects=False
        )
        if resp.status_code != _StatusCodes.OK:
            self._expired = True
            # In the absence of a successful response, assume the refresh token is expired. This should indicate
            # to the caller that the AuthorizationClient is defunct and a new one needs to be re-initialized.

            _keyring.delete_password(_keyring_service_name, _keyring_access_token_storage_key)
            _keyring.delete_password(_keyring_service_name, _keyring_refresh_token_storage_key)
            return
        self._initialize_credentials(resp) 
Example #7
Source File: requests.py    From sunnyportal-py with GNU General Public License v3.0 6 votes vote down vote up
def perform(self, connection):
        assert self.url is not None

        self.log_request(self.method, self.url)
        connection.request(self.method, self.url)

        response = connection.getresponse()
        if response.status != http.OK:
            raise RuntimeError(
                "HTTP error performing {} request: {} {}".format(
                    self.service, response.status, response.reason
                )
            )

        data = response.read().decode("utf-8")
        return self.handle_response(data) 
Example #8
Source File: test_connector.py    From sushy with Apache License 2.0 6 votes vote down vote up
def test_timed_out_session_re_established(self):
        self.auth._session_key = 'asdf1234'
        self.auth.get_session_key.return_value = 'asdf1234'
        self.conn._auth = self.auth
        self.session = mock.Mock(spec=requests.Session)
        self.conn._session = self.session
        self.request = self.session.request
        first_response = mock.MagicMock()
        first_response.status_code = http_client.FORBIDDEN
        second_response = mock.MagicMock()
        second_response.status_code = http_client.OK
        second_response.json = {'Test': 'Testing'}
        self.request.side_effect = [first_response, second_response]
        response = self.conn._op('POST', path='fake/path', data=self.data,
                                 headers=self.headers)
        self.auth.refresh_session.assert_called_with()
        self.assertEqual(response.json, second_response.json) 
Example #9
Source File: end_to_end_test.py    From JediHTTP with Apache License 2.0 6 votes vote down vote up
def test_client_python3_specific_syntax_completion(jedihttp):
    filepath = utils.fixture_filepath('py3.py')
    request_data = {
        'source': read_file(filepath),
        'line': 19,
        'col': 11,
        'source_path': filepath
    }

    response = requests.post('http://127.0.0.1:{0}/completions'.format(PORT),
                             json=request_data,
                             auth=HmacAuth(SECRET))

    assert_that(response.status_code, equal_to(httplib.OK))

    hmachelper = hmaclib.JediHTTPHmacHelper(SECRET)
    assert_that(hmachelper.is_response_authenticated(response.headers,
                                                     response.content)) 
Example #10
Source File: end_to_end_test.py    From JediHTTP with Apache License 2.0 6 votes vote down vote up
def test_client_request_with_parameters(jedihttp):
    filepath = utils.fixture_filepath('goto.py')
    request_data = {
        'source': read_file(filepath),
        'line': 10,
        'col': 3,
        'source_path': filepath
    }

    response = requests.post(
        'http://127.0.0.1:{0}/gotodefinition'.format(PORT),
        json=request_data,
        auth=HmacAuth(SECRET))

    assert_that(response.status_code, equal_to(httplib.OK))

    hmachelper = hmaclib.JediHTTPHmacHelper(SECRET)
    assert_that(hmachelper.is_response_authenticated(response.headers,
                                                     response.content)) 
Example #11
Source File: process.py    From pyngrok with MIT License 6 votes vote down vote up
def healthy(self):
        """
        Check whether the :code:`ngrok` process has finished starting up and is in a running, healthy state.

        :return: :code:`True` if the :code:`ngrok` process is started, running, and healthy, :code:`False` otherwise.
        :rtype: bool
        """
        if self.api_url is None or \
                not self._tunnel_started or not self._client_connected:
            return False

        if not self.api_url.lower().startswith("http"):
            raise PyngrokSecurityError("URL must start with \"http\": {}".format(self.api_url))

        # Ensure the process is available for requests before registering it as healthy
        request = Request("{}/api/tunnels".format(self.api_url))
        response = urlopen(request)
        if response.getcode() != StatusCodes.OK:
            return False

        return self.proc.poll() is None and \
               self.startup_error is None 
Example #12
Source File: test_entity_mixins.py    From nailgun with GNU General Public License v3.0 6 votes vote down vote up
def test_delete_v6(self):
        """
        What happens if the server returns an HTTP OK status and blank only
        content?
        """
        response = mock.Mock()
        response.status_code = http_client.OK
        response.content = ' '
        with mock.patch.object(
            entity_mixins.EntityDeleteMixin,
            'delete_raw',
            return_value=response,
        ):
            with mock.patch.object(entity_mixins, '_poll_task') as poll_task:
                self.assertEqual(self.entity.delete(), None)
        self.assertEqual(poll_task.call_count, 0) 
Example #13
Source File: http.py    From scroll-phat-hd with MIT License 6 votes vote down vote up
def scroll():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("scroll", (int(data["x"]), int(data["y"]))))
    except KeyError:
        response = {"result": "KeyError", "error": "keys x and y not posted."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except ValueError:
        response = {"result": "ValueError", "error": "invalid integer."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
Example #14
Source File: http.py    From scroll-phat-hd with MIT License 6 votes vote down vote up
def autoscroll():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("autoscroll", (data["is_enabled"], float(data["interval"]))))
    except KeyError:
        response = {"result": "KeyError", "error": "keys is_enabled and interval not posted."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except ValueError:
        response = {"result": "ValueError", "error": "invalid data type(s)."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
Example #15
Source File: cvpysdk.py    From cvpysdk with Apache License 2.0 6 votes vote down vote up
def _logout(self):
        """Posts a logout request to the server.

            Returns:
                str     -   response string from server upon logout success

        """
        flag, response = self.make_request('POST', self._commcell_object._services['LOGOUT'])

        if flag:
            self._commcell_object._headers['Authtoken'] = None

            if response.status_code == httplib.OK:
                return response.text
            else:
                return 'Failed to logout the user'
        else:
            return 'User already logged out' 
Example #16
Source File: test_httplib.py    From android_universal with MIT License 6 votes vote down vote up
def test_response_headers(self):
        # test response with multiple message headers with the same field name.
        text = ('HTTP/1.1 200 OK\r\n'
                'Set-Cookie: Customer="WILE_E_COYOTE"; '
                'Version="1"; Path="/acme"\r\n'
                'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
                ' Path="/acme"\r\n'
                '\r\n'
                'No body\r\n')
        hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
               ', '
               'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
        s = FakeSocket(text)
        r = client.HTTPResponse(s)
        r.begin()
        cookies = r.getheader("Set-Cookie")
        self.assertEqual(cookies, hdr) 
Example #17
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_processes(self):
        resp = self.client.get('/processes')
        self.assertEqual(resp.status_code, httplib.OK) 
Example #18
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_works_on_prefix(self):
        r = PsDashRunner({'PSDASH_URL_PREFIX': self.default_prefix})
        resp = r.app.test_client().get(self.default_prefix)
        self.assertEqual(resp.status_code, httplib.OK) 
Example #19
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_missing_starting_slash_works(self):
        r = PsDashRunner({'PSDASH_URL_PREFIX': 'subfolder/'})
        resp = r.app.test_client().get('/subfolder/')
        self.assertEqual(resp.status_code, httplib.OK) 
Example #20
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_index(self):
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, httplib.OK) 
Example #21
Source File: test_httplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_read_head(self):
        # Test that the library doesn't attempt to read any data
        # from a HEAD request.  (Tickles SF bug #622042.)
        sock = FakeSocket(
            'HTTP/1.1 200 OK\r\n'
            'Content-Length: 14432\r\n'
            '\r\n',
            NoEOFBytesIO)
        resp = client.HTTPResponse(sock, method="HEAD")
        resp.begin()
        if resp.read():
            self.fail("Did not expect response from HEAD request") 
Example #22
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_disks(self):
        resp = self.client.get('/disks')
        self.assertEqual(resp.status_code, httplib.OK) 
Example #23
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_process_memory(self):
        resp = self.client.get('/process/%d/memory' % self.pid)
        self.assertEqual(resp.status_code, httplib.OK) 
Example #24
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_missing_trailing_slash_works(self):
        r = PsDashRunner({'PSDASH_URL_PREFIX': '/subfolder'})
        resp = r.app.test_client().get('/subfolder/')
        self.assertEqual(resp.status_code, httplib.OK) 
Example #25
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_process_overview(self):
        resp = self.client.get('/process/%d' % self.pid)
        self.assertEqual(resp.status_code, httplib.OK) 
Example #26
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_process_children(self):
        resp = self.client.get('/process/%d/children' % self.pid)
        self.assertEqual(resp.status_code, httplib.OK) 
Example #27
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_process_connections(self):
        resp = self.client.get('/process/%d/connections' % self.pid)
        self.assertEqual(resp.status_code, httplib.OK) 
Example #28
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_process_environment(self):
        resp = self.client.get('/process/%d/environment' % self.pid)
        self.assertEqual(resp.status_code, httplib.OK) 
Example #29
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_process_threads(self):
        resp = self.client.get('/process/%d/threads' % self.pid)
        self.assertEqual(resp.status_code, httplib.OK) 
Example #30
Source File: test_web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def test_multiple_remote_addresses_using_list(self):
        r = PsDashRunner({'PSDASH_ALLOWED_REMOTE_ADDRESSES': ['127.0.0.1', '10.0.0.1']})

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '10.0.0.1'})
        self.assertEqual(resp.status_code, httplib.OK)

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '127.0.0.1'})
        self.assertEqual(resp.status_code, httplib.OK)

        resp = r.app.test_client().get('/', environ_overrides={'REMOTE_ADDR': '10.124.0.1'})
        self.assertEqual(resp.status_code, httplib.UNAUTHORIZED)