Use Django decorators in DSG

In Django, decorators expect to decorate a function that takes a django.http.HttpRequest as its first argument and return a django.http.HttpResponse.

In DSG, decorators expect to decorate a class method that take 2 arguments: a `grpc Message<https://grpc.io/docs/languages/python/quickstart/#update-the-server>`_ as request and the grpc context, and return a grpc Message as response.

Both are based on HTTP protocol. So it’s possible to find similar concept and usage.

By using DSG proxy request and proxy response it is possible to simulate django behavior and apply it to gRPC calls.

See http_to_grpc decorator for more detailsa and parameters.

Simple example

from django_socio_grpc.decorators import http_to_grpc
from django.views.decorators.vary import vary_on_headers

def vary_on_metadata(*headers):
    return http_to_grpc(vary_on_headers(*headers))

Example with method decorator and data variance

In the following example we are transforming a function decorator into a method decorator. Then we are transforming it to a grpc decorator. In the same time we specify that for each simulate Django request we want to set the method attribute to the value GET (this is because grpc only use POST request and Django only cache GET request) Also cache_page is not fully supporting async for now if you are using DB cache backend so we disable async support. Feel free to set it to True in you own decorator if using an async compatible cache backend.

The functools.wraps is optional and is used to keep the original function name and docstring.

from django_socio_grpc.decorators import http_to_grpc
from django.views.decorators.cache import cache_page


@functools.wraps(cache_page)
def cache_endpoint(*args, **kwargs):
    return http_to_grpc(
        method_decorator(cache_page(*args, **kwargs)),
        request_setter={"method": "GET"},
        support_async=False
    )