Ejemplo n.º 1
0
    def create_image_from_socket(self, msg):
        """
        Create an image from data received on the socket.

        This callback function is called when data is ready on the IPC channel. It creates
        the image data array from the raw data sent by the Odin Data Plugin, reshaping
        it to a multi dimensional array matching the image dimensions.
        :param msg: a multipart message containing the image header, and raw image data.
        """
        # Message should be a list from multi part message.
        # First part will be the json header from the live view, second part is the raw image data
        header = json_decode(msg[0])

        # json_decode returns dictionary encoded in unicode. Convert to normal strings if necessary.
        header = convert_unicode_to_string(header)
        logging.debug("Got image with header: %s", header)

        # Extract the type of the image data from the header. If the type is float, coerce to
        # float32 since the native float in HDF5 is 32-bit vs 64-bit in python and numpy.
        dtype = header['dtype']
        if dtype == 'float':
            dtype = 'float32'

        # create a np array of the image data, of type specified in the frame header
        img_data = np.fromstring(msg[1], dtype=np.dtype(dtype))

        self.img_data = img_data.reshape([int(header["shape"][0]), int(header["shape"][1])])
        self.header = header

        self.rendered_image = self.render_image(
            self.selected_colormap, self.clip_min, self.clip_max)
Ejemplo n.º 2
0
    def put(self, path, request):
        """Handle an HTTP PUT request.

        This method handles an HTTP PUT request, returning a JSON response.

        :param path: URI path of request
        :param request: HTTP request object
        :return: an ApiAdapterResponse object containing the appropriate response
        """

        content_type = 'application/json'

        try:
            data = convert_unicode_to_string(decode_request_body(request))
            self.qem_detector.set(path, data)
            response = self.qem_detector.get(path)
            status_code = 200
        except QemDetectorError as e:
            response = {'error': str(e)}
            status_code = 400
        except (TypeError, ValueError) as e:
            response = {
                'error': 'Failed to decode PUT request body: {}'.format(str(e))
            }
            status_code = 400

        logging.debug(response)

        return ApiAdapterResponse(response,
                                  content_type=content_type,
                                  status_code=status_code)
Ejemplo n.º 3
0
 def test_convert_unicode_to_string_mixed_recursion(self):
     u_object = {u'string': u'test string',
                 u'list': [u'unicode string', "normal string"]
                 }
     result = util.convert_unicode_to_string(u_object)
     expected_result = {
                         'string': 'test string',
                         'list': ['unicode string', "normal string"]
                       }
     assert_equal(result, expected_result)
Ejemplo n.º 4
0
 def test_convert_unicode_to_string_mixed_recursion(self):
     """Test recursion through a deeper object with mixed types."""
     u_object = {u'string': u'test string',
                 u'list': [u'unicode string', "normal string"]
                 }
     result = util.convert_unicode_to_string(u_object)
     expected_result = {
                         'string': 'test string',
                         'list': ['unicode string', "normal string"]
                       }
     assert result == expected_result
Ejemplo n.º 5
0
    def put(self, path, request):
        """
        Handle an HTTP PUT request.

        This method handles an HTTP PUT request, returning a JSON response.

        :param path: URI path of request
        :param request: HTTP request object
        :return: an ApiAdapterResponse object with the appropriate response
        """
        content_type = 'application/json'
        status_code = 200
        response = {}
        checkAdapters = True if len(path) > 0 else False
        requestSent = False
        try:
            if checkAdapters:
                for name, adapter in self.adapters.items():
                    if path.startswith(name):

                        relative_path = path.split(name + '/')
                        reply = adapter.put(path=relative_path[1],
                                            request=request)
                        requestSent = True
                        if reply.status_code != 200:
                            status_code = reply.status_code
                            response = reply.data
                            logging.debug(response)
                            return ApiAdapterResponse(
                                response,
                                content_type=content_type,
                                status_code=status_code)

            # Only pass request to Hexitec member if no matching adapter found
            if requestSent is False:
                data = convert_unicode_to_string(decode_request_body(request))
                self.hexitec.set(path, data)
                response = self.hexitec.get(path)
        except HexitecError as e:
            response = {'error': str(e)}
            status_code = 400
        except (TypeError, ValueError) as e:
            response = {
                'error': 'Failed to decode PUT request body: {}'.format(str(e))
            }
            status_code = 400

        logging.debug(response)

        return ApiAdapterResponse(response,
                                  content_type=content_type,
                                  status_code=status_code)
Ejemplo n.º 6
0
    async def test_adapter_put_proxy_path(self, async_proxy_adapter_test):
        """
        Test that a PUT to a sub-path without a trailing slash in the URL within a targer succeeds
        and returns the correct data.
        """
        node = async_proxy_adapter_test.adapter.targets[0].name
        path = "more"
        async_proxy_adapter_test.request.body = '{"replace": "been replaced"}'
        response = await async_proxy_adapter_test.adapter.put(
            "{}/{}".format(node, path), async_proxy_adapter_test.request)

        assert async_proxy_adapter_test.adapter.param_tree.get('')['status'][node]['status_code'] == 200
        assert convert_unicode_to_string(response.data["more"]["replace"]) == "been replaced"
Ejemplo n.º 7
0
    def put(self, path):
        """Handle PUT requests to the test server."""
        response_body = convert_unicode_to_string(tornado.escape.json_decode(self.request.body))
        try:
            self.param_tree.set(path, response_body)
            data_ref = self.param_tree.get(path)

            self.write(data_ref)
        except ParameterTreeError:
            self.set_status(404)
            self.write_error(404)
        except Exception as other_e:
            logging.error("ProxyTestHandler PUT failed: %s", str(other_e))
            self.write_error(500)
Ejemplo n.º 8
0
    async def test_adapter_put(self, async_proxy_adapter_test):
        """
        Test that a PUT request to the proxy adapter returns the appropriate data for all
        defined proxied targets.
        """
        response = await async_proxy_adapter_test.adapter.put(
            async_proxy_adapter_test.path, async_proxy_adapter_test.request)

        assert 'status' in response.data

        assert len(response.data) == async_proxy_adapter_test.num_targets + 1

        for tgt in range(async_proxy_adapter_test.num_targets):
            node_str = 'node_{}'.format(tgt)
            assert node_str in response.data
            assert convert_unicode_to_string(response.data[node_str]) == ProxyTestHandler.param_tree.get("")
Ejemplo n.º 9
0
 def test_convert_unicode_to_string_dict(self):
     """Test conversion of a unicode dict to native string dict."""
     u_dict = {u'key': u'value'}
     result = util.convert_unicode_to_string(u_dict)
     assert result == {"key": "value"}
Ejemplo n.º 10
0
 def test_convert_unicode_to_string_list(self):
     """Test conversion of a list of unicode strings to strings."""
     u_list = [u'first string', u'second string']
     result = util.convert_unicode_to_string(u_list)
     assert result == ["first string", "second string"]
Ejemplo n.º 11
0
 def test_convert_unicode_to_string(self):
     """Test conversion of unicode to string."""
     u_string = u'test string'
     result = util.convert_unicode_to_string(u_string)
     assert result == "test string"
Ejemplo n.º 12
0
 def test_convert_unicode_to_string_dict(self):
     u_dict = {u'key': u'value'}
     result = util.convert_unicode_to_string(u_dict)
     assert_equal(result, {"key": "value"})
Ejemplo n.º 13
0
 def test_convert_unicode_to_string_list(self):
     u_list = [u'first string', u'second string']
     result = util.convert_unicode_to_string(u_list)
     assert_equal(result, ["first string", "second string"])
Ejemplo n.º 14
0
 def test_convert_unicode_to_string(self):
     u_string = u'test string'
     result = util.convert_unicode_to_string(u_string)
     assert_equal(result, "test string")