Django 3.1 async view with login_required decorator

Viewed 1108

I try to use an async view that is decorated somewhere by login_required.
Currently i decorate it in my urls.py

urls.py:

from . import views
from django.urls import path
from django.contrib.auth.decorators import login_required

urlpatterns = [
    path('', login_required(views.my_view), name='my_view'),
]

views.py:

async def my_view(request):
return render(request, 'app/test.html', context={})

When tested it I get an error that this view would return an unawaited coroutine

When render is awaited, it tells me that i cannot await a http response.

views.py:

@async_to_sync
async def my_view(request):
return render(request, 'app/test.html', context={})

Seems to work but,
in my understanding @async_to_sync should turn it synchronus, but executes it asyncronous?

edit:
without login_required @async_to_sync does not seem to be required and it works.

what is the the proper way to do it?

2 Answers

You'd probably need to write an async-aware version of the login_required decorator.

Not that it'd help you much at present, I'd wager: If you're using the default auth backend, accessing request.user would involve a database access, which are still synchronous.

You might want to do this:

@sync_to_async
@login_required
def my_view(request):
    ...

Note that the order of the decorators are important

Related