如何在Django中通过基于类的视图(CBV)实现异步视图

dpiehjr4  于 2023-05-23  发布在  Go
关注(0)|答案(1)|浏览(325)

在django(CBV)中尝试将异步视图作为基于类的视图操作时发生AssertionError
我写的Python代码如下。

url.py

from django.contrib import admin
from django.conf.urls import include
from django.urls import re_path
from rest_framework import routers
from blog import views

router = routers.DefaultRouter()

router.register(r'test', views.TestView, 'hello')

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'', include(router.urls)),
    re_path(r'async_view/', include(router.urls))
]

views.py

class TestView(viewsets.ViewSet):
    LOG = logging.getLogger('test')
    async def list(self, request, *args, **kwargs):
        self.LOG.info("async method start!!")
        queryset = Post.objects.none
        await asyncio.sleep(3)
        return HttpResponse("Hello async world!")

asgi.py

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

application = get_asgi_application()

当我执行下面的命令

uvicorn mysite.asgi:application --limit-concurrency 12 --reload --host 0.0.0.0 --port 80

然后,发生AssertionError

AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>`

哪部分错了??

相关问题