这在 Django 3.1+ 中是可能的,在 introducing asynchronous support 之后。
关于异步运行循环,您可以通过使用uvicorn 或任何其他ASGI 服务器而不是gunicorn 或其他WSGI 服务器运行Django 来使用它。
不同之处在于,在使用 ASGI 服务器时,已经有一个运行循环,而在使用 WSGI 时则需要创建一个。使用 ASGI,您可以直接在 views.py 或其 View Classes 的继承函数下定义 async 函数。
假设您使用 ASGI,您有多种方法可以实现这一点,我将描述其中的几种(例如,其他选项可以使用 asyncio.Queue):
- 使
start()异步
通过使start()异步,您可以直接使用现有的运行循环,通过使用asyncio.Task,您可以触发并忘记到现有的运行循环。如果你想开火但要记住,你可以创建另一个Task 来跟进这个,即:
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.conf import settings
from mycrawler import tasks
import asyncio
async def update_all_async(deep_crawl=True, season=settings.CURRENT_SEASON, log_to_db=True):
await tasks.update_all(deep_crawl, season, log_to_db)
async def follow_up_task(task: asyncio.Task):
await asyncio.sleep(5) # Or any other reasonable number, or a finite loop...
if task.done():
print('update_all task completed: {}'.format(task.result()))
else:
print('task not completed after 5 seconds, aborting')
task.cancel()
@api_view(['POST', 'GET'])
async def start(request):
"""
Start crawling.
"""
if request.method == 'POST':
print("Crawler: start {}".format(request))
deep = request.data.get('deep', False)
season = request.data.get('season', settings.CURRENT_SEASON)
# Once the task is created, it will begin running in parallel
loop = asyncio.get_running_loop()
task = loop.create_task(update_all_async(season=season, deep_crawl=deep))
# Fire up a task to track previous down
loop.create_task(follow_up_task(task))
return Response({"Success": {"crawl finished"}}, status=status.HTTP_200_OK)
else:
return Response ({"description": "Start the crawler by calling this enpoint via post.", "allowed_parameters": {
"deep": "boolean",
"season": "number"
}}, status.HTTP_200_OK)
- async_to_sync
有时您不能只使用async 函数将请求首先路由到as it happens with DRF(截至今天)。
为此,Django 提供了一些有用的async adapter functions,但请注意,从同步上下文切换到异步上下文或反之亦然,a small performance penalty 大约需要 1 毫秒。请注意,这一次,在 update_all_sync 函数中收集的运行循环改为:
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.conf import settings
from mycrawler import tasks
import asyncio
from asgiref.sync import async_to_sync
@async_to_sync
async def update_all_async(deep_crawl=True, season=settings.CURRENT_SEASON, log_to_db=True):
#We can use the running loop here in this use case
loop = asyncio.get_running_loop()
task = loop.create_task(tasks.update_all(deep_crawl, season, log_to_db))
loop.create_task(follow_up_task(task))
async def follow_up_task(task: asyncio.Task):
await asyncio.sleep(5) # Or any other reasonable number, or a finite loop...
if task.done():
print('update_all task completed: {}'.format(task.result()))
else:
print('task not completed after 5 seconds, aborting')
task.cancel()
@api_view(['POST', 'GET'])
def start(request):
"""
Start crawling.
"""
if request.method == 'POST':
print("Crawler: start {}".format(request))
deep = request.data.get('deep', False)
season = request.data.get('season', settings.CURRENT_SEASON)
# Make update all "sync"
sync_update_all_sync = async_to_sync(update_all_async)
sync_update_all_sync(season=season, deep_crawl=deep)
return Response({"Success": {"crawl finished"}}, status=status.HTTP_200_OK)
else:
return Response ({"description": "Start the crawler by calling this enpoint via post.", "allowed_parameters": {
"deep": "boolean",
"season": "number"
}}, status.HTTP_200_OK)
在这两种情况下,函数都会快速返回 200,但从技术上讲,第二个选项更慢。
重要提示:在使用 Django 时,这些异步操作通常会涉及数据库操作。至少目前,Django 中的数据库操作只能是同步的,因此您必须在异步上下文中考虑这一点。 sync_to_async() 在这些情况下变得非常方便。