Exemplo n.º 1
0
def get_rpc_application():
    """Creates a Gunicorn Thrift compatible TProcessor and initializes NewRelic
    """
    global __new_relic

    _init_django()

    if agent and not __new_relic:  # pragma: no cover
        try:
            agent.initialize()
            logging.info('Initialized New Relic application')
            __new_relic = True
        except Exception as exc:  # pylint: disable=all
            logging.warning(
                'Could not wrap RPC server in New Relic config. Exc: %s', exc)

    for i_app in settings.INSTALLED_APPS:
        if i_app.startswith('django') or 'manifold' in i_app:
            continue
        try:
            importlib.import_module("%s.views" % i_app)
        except ImportError:  # pragma: no cover
            logging.info(
                'No module "%s.views" found, skipping RPC calls from it...',
                i_app)

    _print_rpc_config()

    return TProcessor(load_service(), handler)
Exemplo n.º 2
0
    def test_make_client(self, mocked_client):
        client = rpc.make_client()
        self.assertIsNotNone(client)

        mocked_client.assert_called_with(load_service(),
                                         host='127.0.0.1',
                                         port=9090)
Exemplo n.º 3
0
 def test_load_service_default(self):
     expected_func_args = [
         'multiVarArgument_args', 'pingPong_args', 'pong_args',
         'simple_args', 'complex_args'
     ]
     service = load_service()
     self.assertTrue(all([hasattr(service, x) for x in expected_func_args]))
Exemplo n.º 4
0
def make_client(key='default'):
    """Creates a client to call functions with

    :param key: Settings key to create client with
    :return: Thriftpy client
    """
    _init_django()

    thrift_settings = settings.MANIFOLD[key]
    host = thrift_settings.get('host', '127.0.0.1')
    port = thrift_settings.get('port', 9090)
    return thrift_client(load_service(key), host=host, port=port)
Exemplo n.º 5
0
def wrap_thrift_function(name, handler_function):
    """Wraps a Thrift handler function in a Django
    :param name: The RPC function name that was called
    :param handler_function: Thrift function to handle RPC
    :return: Function that can be called with path()
    """
    service = load_service()
    thrift_args = getattr(service, f'{name}_args').thrift_spec

    @csrf_exempt
    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)

    return request_handler
Exemplo n.º 6
0
 def test_load_service_key(self):
     expected_func_args = ['deadFunction_args']
     service = load_service(key='non-default')
     self.assertTrue(all([hasattr(service, x) for x in expected_func_args]))