首页 > 解决方案 > 如何在 django 视图中使用'async def'?

问题描述

#views.py

async def test(request: ASGIRequest):
    return HttpResponse(b'hello')

class Test(View):
    async def get(self, request: ASGIRequest):
        print(type(request))
        print(dir(self))
        return HttpResponse(b'hello')
#urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'testfunc/', test),
    path(r'testclass/', Test.as_view()),
]

我明白了:

AttributeError at /testclass/
'coroutine' object has no attribute 'get'

##########

AttributeError at /testfunc/
'coroutine' object has no attribute 'get'

标签: pythondjangoasynchronousasgi

解决方案


在 django 3.0 中,他们开始添加 django 支持,但这并不意味着我们可以使用异步视图或中间件。

在此处阅读更多信息: https ://docs.djangoproject.com/en/3.0/topics/async/


推荐阅读