Opened 4 years ago
Closed 4 years ago
#32077 closed New feature (duplicate)
HTTP view decorators (require_http_methods) not working with async views
Reported by: | Hendrik Frentrup | Owned by: | nobody |
---|---|---|---|
Component: | HTTP handling | Version: | 3.1 |
Severity: | Normal | Keywords: | async views decorators |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
HTTP view decorators don't work with async views, though I don't see why they shouldn't given they don't use the ORM (unlike the login_required decorator for example).
The following throws a ValueError
@require_http_methods(['GET']) async def blog_info(request, blog_id): blog = await sync_to_async(Blog.objects.get)(id=blog_id) return HttpResponse(f"got spot #id: {blog_id} - name: {blog.name}")
Here is the error:
ValueError: The view myapp.views.blog_info didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view.
From what I can see this is due to the decorator calling the async function after checking the request headers and returning but returning a non-async function (return inner
) in django.views.decorators.http
How to handle middleware with async seems to be a point of contention still, but these decorators are hardly middleware, so I think it would be worth fixing. From some initial testing, it doesn't seem to be a difficult fix either.
By the way, the initial testing yielded this [potential fix] https://github.com/hendrikfrentrup/django/commit/8e726875270e7a7062f246709c131915276b88ab The test for sync views all pass, but I guess a set of tests for async views would be required. Will have a look into how to write async tests. Any comments more than welcome.