Search code examples
djangointerceptorgrpc-python

django grpc framework server interceptor does not seem to run properly


I am using djangogrpcframework 0.2.1 and I am trying to write a interceptor to see if a key is present in the request metadata. I also log somethings to see the progress of the interceptor.

from grpc import ServerInterceptor, StatusCode


class CustomInterceptor(ServerInterceptor):

    def intercept_service(self, continuation, handler_call_details):
        print("start intercepting")
        metadata = handler_call_details.invocation_metadata

        if 'key' not in metadata:
            context = handler_call_details.invocation_metadata.context()
            context.abort(StatusCode.UNAVAILABLE, 'No key provided')

        return continuation(handler_call_details)

This class is located in path/to/CustomInterceptor. I have added this interceptor to my django project settings like this:

GRPC_FRAMEWORK = {
    'ROOT_HANDLERS_HOOK': "project.urls.grpc_handlers",
    'SERVER_INTERCEPTORS': [
        "path.to.CustomInterceptor",
    ]
}

I run grpc server with the command:

python manage.py grpcrunserver

When trying to call any handler from a golang client to this server I do not see any log of the progress of interceptor, and I get the following error on my client

rpc error: code = Unknown desc = Error in service handler!

I already tried to see if the server has successfully imported the interceptor and that was not the problem. I tried setting GRPC_VERBOSITY=DEBUG to see any log of error on my server but there was no log.


Solution

  • When using command to run the grpc server, it seems that any CustomInterceptor is not initialized and therefore, an error is raise due to wrong number of input arguments for intercept_service function. So I changed the function into a staticmethod and everything worked fine.

    @staticmethod
    def intercept_service(continuation, handler_call_details):
        print("start intercepting")
        metadata = handler_call_details.invocation_metadata
    
        if 'key' not in metadata:
            context = handler_call_details.invocation_metadata.context()
            context.abort(StatusCode.UNAVAILABLE, 'No key provided')
    
        return continuation(handler_call_details)