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

Improve typing of view decorators

Open Viicos opened this issue 1 year ago • 4 comments

A new type variable is defined, matching (async) callables taking a request and returning a response.

Some decorators are defined as views to comply with pyright (see https://github.com/microsoft/pyright/issues/5821#issuecomment-1694422066 for an explanation).

Note that some decorators allow *args, **kwargs to exist on the decorated views, e.g. never_cache:

def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will never be cached.
    """

    if iscoroutinefunction(view_func):

        async def _view_wrapper(request, *args, **kwargs):
            _check_request(request, "never_cache")
            response = await view_func(request, *args, **kwargs)
            add_never_cache_headers(response)
            return response

    else:

        def _view_wrapper(request, *args, **kwargs):
            _check_request(request, "never_cache")
            response = view_func(request, *args, **kwargs)
            add_never_cache_headers(response)
            return response

    return wraps(view_func)(_view_wrapper)

However, I think it's good to actually enforce views to take a single request argument. What do you think?

Viicos avatar May 15 '24 16:05 Viicos

However, I think it's good to actually enforce views to take a single request argument. What do you think?

What about path parameters?

flaeppe avatar May 15 '24 19:05 flaeppe

It's probably fine to keep the first positional argument a request, but it needs to allow an arbitrary amount of args and kwargs after that

flaeppe avatar May 15 '24 20:05 flaeppe

However, I think it's good to actually enforce views to take a single request argument. What do you think?

I believe it would break the hack that our FAQ suggests to constrain request.user type for authenticated views? https://github.com/typeddjango/django-stubs?tab=readme-ov-file#how-can-i-create-a-httprequest-thats-guaranteed-to-have-an-authenticated-user

I never liked this hack to begin with (https://github.com/typeddjango/django-stubs/discussions/2046#discussioncomment-9048731), but I think lots of users are relying on it, we shouldn't break it, unless there's strong consensus to do so.

intgr avatar May 16 '24 14:05 intgr

The AuthenticatedHttpRequest think is annoying :/ Maybe it could be explicitly exported in django-stubs-ext or in the stubs itself, and added as an overload?

Viicos avatar May 30 '24 20:05 Viicos