我正在努力学习视频教程,并try 理解Django中的异步视图和@sync_to_async修饰器.
我有这样的代码:
import time
import asyncio
from asgiref.sync import sync_to_async
from django.http import HttpResponse
from movies.models import Movie
from stories.models import Story
@sync_to_async
def get_movies_async():
print('prepare to get the movies...')
time.sleep(2)
qs = Movie.objects.all()
print('got all the movies')
@sync_to_async
def get_stories_async():
print('prepare to get the stories...')
time.sleep(5)
qs = Story.objects.all()
print('got all the stories')
async def main_view_async(request):
start_time = time.time()
await asyncio.gather(get_movies_async(), get_stories_async())
total = (time.time() - start_time)
print("total: ", total)
return HttpResponse('async!')
But when I call main_view_async from my browser it still takes 7 seconds, not 5 seconds like in the video tutorial.
The tutorial might be outdated (year 2020). Or perhaps I am doing something wrong? Can you please help?
My output
prepare to get the movies...
got all the movies
prepare to get the stories...
got all the stories
total: 7.0126471519470215
The tutorial terminal output个
prepare to get the movies...
prepare to get the stories...
got all the movies
got all the stories
total: 5.0126471519470215