问题描述
我正在尝试使用全新的 Django 3.1
异步视图类.根据可用的有限文档,我尝试创建自己的 async def __call __()
方法.从文档中:
I am trying to use the very new Django 3.1
Async view classes.Based on the limited documentation available, I have tried to create my own async def __call__()
method.From the documents:
但是,到目前为止,我还没有编写基于异步类的视图的运气.我经常收到 await
异常,或者 asyncio.iscoroutinefunction
返回 False
,如果类实际上是异步的,我认为应该返回true.
However, until now I have had no luck with writing an asynchronous class based view. I constantly get await
exceptions, or asyncio.iscoroutinefunction
returns False
, which I assume should return true if the class is actually Asynchronous.
由于文档中缺少示例,因此对异步编程有更多了解的人可以通过基于类的异步视图的示例来帮助我吗?
Since the documentation is lacking an example, could someone with more knowledge of async programming help me with an example of a class based asynchronous view?
推荐答案
花很多时间在Django票务系统,博客文章(向Joren致谢)等方面进行搜索,所以您不必这样做.
Spend quite some time searching in the Django ticket system, blogposts (thx to Joren), etc. so you don't have to.
最好的办法就是使用博客:
class YourView(View):
@classonlymethod
def as_view(cls, **initkwargs):
view = super().as_view(**initkwargs)
view._is_coroutine = asyncio.coroutines._is_coroutine
return view
async def get(self, *args, **kwargs):
...
但是您还需要知道,您无法使用实际的泛型(没有异步ORM支持,甚至TemplateView也无法使用)和内置装饰器(适用于3.1).您需要为Django通常自己做的事情写自己的东西.
But you also need to be aware there is no way you can use actual generics (no async ORM support, even TemplateView doesn't work) and build-in decorators for 3.1. You need to write your own stuff for things that Django normally does itself.
这篇关于在Django中使用基于异步类的视图的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!