def request_handler(request): """The request handler Django uses for each call :param request: Django request :return: Django JsonResponse """ try: # Run the thrift handler function with JSON kwargs if thrift_args: response = _handle_arg_function(handler_function, request, thrift_args) else: response = serialize(handler_function()) except KeyError as exc: logger.error(f"Invalid HTTP args to '{name}': {str(exc)}") return JsonResponse({'response': 'error', 'error': str(exc)}) except TypeError as exc: logger.error( f"Invalid HTTP args to '{name}', check JSON: {str(exc)}") error = 'Invalid Thrift request.' if 'unexpected' in str(exc): error = 'Unable to coerce keywords into handler.' elif 'required' in str(exc): error = 'Missing Thrift keys.' return JsonResponse({'response': 'error', 'error': error}) except thriftpy.thrift.TException as exc: # Handle Thrift Exceptions return JsonResponse({ 'response': 'error', 'exception': serialize(exc), 'exceptionType': str(type(exc).__name__) }) return JsonResponse({'return': response, 'response': 'ok'}, safe=False)
def test_primitive_serializer(self): expected = [1, 2, 3] result = serialize([1, 2, 3]) self.assertEqual(expected, result) expected = 5 result = serialize(5) self.assertEqual(expected, result) expected = None result = serialize(None) self.assertEqual(expected, result) expected = {'hello': 'world', 'nested': {'woah': 'baby'}} result = serialize(expected) self.assertEqual(expected, result)
def __init__(self, struct, *args, **kwargs): """Serializes Thrift struct if needed so it can be cleaned """ self.struct = struct self._errors = [] if not isinstance(struct, dict): struct = serialize(struct) super().__init__(data=struct, *args, **kwargs)
def test_object_serializer(self): module = load_module() expected = { 'some_string': 'hello world', 'innerStruct': { 'val': 123, } } test_struct = module.ContainedStruct(some_string='hello world', innerStruct=module.InnerStruct( val=123, )) result = serialize(test_struct) self.assertEqual(result, expected)
def _handle_arg_function(handler_func, request, thrift_args): """Parse, deserialize, and call RPC handler from Django request :param handler_func: Thrift handler function (the decorated function) :param request: Django request with body :param thrift_args: Thrift function arguments from the service.thrift_spec :return: Dictionary serialized response from RPC function """ try: body = request.body.decode('utf-8') except (UnicodeDecodeError, UnicodeError): body = request.body try: # Try to load any params given data = json.loads(body) except ValueError as exc: logger.warning(f'Could not parse JSON content "{body}": {str(exc)}') data = None arguments = _parse_json_args_to_list(thrift_args, data) return serialize(handler_func(*arguments))