django-ninja
django-ninja copied to clipboard
[BUG] Decorators on operations are ignored
Describe the bug
Any decorator added to an operation isn't run. Consider below, where I'd like my hello_world operation to respond with a set cookie header including a csrftoken cookie.
from django.views.decorators.csrf import ensure_csrf_cookie
from ninja import NinjaAPI
api = NinjaAPI()
@ensure_csrf_cookie
@api.get("/hello")
def hello_world(request):
return "Hello world"
I'm fully aware of that in case process_view or process_response of the ensure_csrf_cookie decorator would've been triggered. I would have received a "Hello world" response (string) value from my operation and not a response object.
Although I'm more interested in how I would proceed to decorate any of my functions being decorated with an api_operation from django ninja. Where I'm able to intercept both the request and response object, just like a django middleware.
Versions (please complete the following information):
- Python version: 3.10
- Django version: 4.1
- Django-Ninja version: 0.19.1
@flaeppe
the router decorator must be the very top one (as it does the final operation preparation and registration)
@api.get("/hello")
@ensure_csrf_cookie
def foo(request....
Yes, I noticed that in the end. But it also forces me to return a HttpResponse from foo.
The idea I had above was about returning e.g. a tuple from foo while still receiving the HttpResponse object (created by django ninja) in process response of ensure_csrf_cookie.
Just in case, I tried to upgrade the documentation in #906 , which may make it clearer how to use ensure_csrf_cookie