django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

Custom ninja HttpRequest class, that includes an 'auth' property

Open geeshta opened this issue 3 years ago • 3 comments

Is your feature request related to a problem? Please describe.

All examples I saw use django.http.HttpRequest to annotate the request object in operations. This is a problem when using an authentication. Now I need to work with request.auth but that property is not defined in the django HttpRequest class which breaks static typechecking (Pyright complains about an unknown property in VS Code for example).

I scanned through ninja codebase to find another request class to use for type hinting but found only this
request.auth = result # type: ignore

Describe the solution you'd like It would be nice to have a ninja-specific request class to use for type hinting that will include an auth property. And maybe it could be used for other stuff in the future as well.

geeshta avatar Mar 26 '22 01:03 geeshta

Hi @geeshta

I guess you can just define custom class and use it in annotations:

from django.http import HttpRequest as DjangoRequest

class HttpRequest(DjangoRequest):
    auth: Any # or your obj

...

@api.get('/test')
def test(request: HttpRequest, foo: int, bar: str):
     ...

vitalik avatar Mar 27 '22 09:03 vitalik

Hi, yes I solved it that way. I just think it would be nice to have an importable class in the Ninja module that is compatible with stuff that Ninja does like authentication. There already is an importable Response class anyway. I'm loving the framework though!

geeshta avatar Mar 27 '22 19:03 geeshta

i wonder if it would be possible to implement the auth hook to work via type annotations (instead of auth= ) which would ensure these two were in sync or even provide direct access to the "user" object as a (type annotated with an Auth type) view param rather than attaching as request.auth

davidszotten avatar Aug 01 '22 15:08 davidszotten