如何在 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'

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

点击此处了解更多信息:https://docs.djangoproject.com/en/3.0/topics/async/

Django 3.0是实现完全异步功能的第一步,但这将是一段漫长的旅程。异步视图目前还不受支持,但在3.x系列的稍后版本中预计会有异步视图。

最新更新