我不太确定我使用的是正确的术语,但我想在函数完成之前访问我的函数返回的项目。例如,我正在开发一个Django项目,我有一个功能可以刮擦一个烹饪网站,并根据你的成分返回你可以烹饪的食谱。
该功能按预期工作,但需要很长时间。我想向用户提供他们可以在找到时烹饪的食谱,而不是他们必须等待整个功能运行,从而加载网页。
我已粘贴下面的相关代码。任何帮助将不胜感激。
def give_recipe_from_ingredients(pantry_items):
for link in get_recipe_links():
current_ingredient_list = []
can_cook = True
grab_from = link
grab_page = urllib.request.urlopen(grab_from)
grab_soup = BeautifulSoup(grab_page, 'html.parser')
rec_title = grab_soup.find('h2', attrs={'entry-title'})
title = rec_title.text.strip()
for ingredient in grab_soup.find_all('span', itemprop="name"):
ingredient_strip = ingredient.text.strip()
current_ingredient_list.append(ingredient_strip)
for item in pantry_items:
for ingredient_in in current_ingredient_list:
if str(item) in ingredient_in:
if title not in recipes_you_can_cook:
yield title
#recipes_you_can_cook.append(title)
#return recipes_you_can_cook
编辑 - 添加了我的views.py文件,以反映我对上述收益的使用。
views.py
@login_required
def pantry(request):
ingredient_list = Ingredient.objects.order_by('-name')[:]
my_generator_instance = give_recipe_from_ingredients(ingredient_list)
for recipe_name in my_generator_instance:
print(recipe_name)
recipes_you_can_cook.append(recipe_name)
context_dict = {'ingredients': ingredient_list, 'recipes': my_generator_instance}
return render(request, 'project/pantry.html', context_dict)
答案 0 :(得分:1)
您可以使用StreamingHttpResponse。请注意,您的Web服务器可能仍会缓冲整个响应,然后再将其发送到客户端。我注意到默认情况下nginx执行此操作(但可以配置),而默认情况下apache会在后端发送响应时发送响应。
如果您选择返回通过JavaScript更新的简短回复,我相信django-channels是可行的方法,虽然我不确定(从未使用它,但它很时尚)。