返回Python中的项目

返回Python中的项目

问题描述:

我不太确定我是否使用了正确的术语,但我希望在函数完成之前访问由我的函数返回的项目。例如,我正在开发一个Django项目,在该项目中,我有一个可以烹饪烹饪网站的功能,并根据您的食材返回您可以烹饪的食谱。返回Python中的项目

该功能按预期工作,但需要很长时间。我想向用户展示他们可以在发现它们时做饭的食谱,而不是等待整个功能运行并因此加载网页。

我粘贴了下面的相关代码。任何帮助将不胜感激。

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) 
+5

看看[yield and generators](https://wiki.python.org/moin/Generators) – danielunderwood

+0

@ danielu13谢谢了!这就像一个魅力的功能,但是我的URL仍然没有加载,直到整个函数完成。我为它添加了新的视图。有什么建议么? – Mir

+1

我会尝试加载没有动态数据的页面,你的函数正在产生,并以某种方式连接到JS来加载它,因为它来了。虽然我并不是那么熟悉web开发,所以我不完全确定。 – danielunderwood

您可以使用StreamingHttpResponse。请注意,您的Web服务器在将其发送到客户端之前可能会缓存整个响应。我注意到,默认情况下,nginx会执行此操作(但可能是可配置的),而默认情况下,apache将发送从后端进来的响应。

如果您选择通过JavaScript更新短回复,我相信django-channels是要走的路,尽管我不确定(从未使用它,但它很时尚)。