2016-11-19 68 views
0

我不太確定我是否使用了正確的術語,但我希望在函數完成之前訪問由我的函數返回的項目。例如,我正在開發一個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

回答

1

您可以使用StreamingHttpResponse。請注意,您的Web服務器在將其發送到客戶端之前可能會緩存整個響應。我注意到,默認情況下,nginx會執行此操作(但可能是可配置的),而默認情況下,apache將發送從後端進來的響應。

如果您選擇通過JavaScript更新短回覆,我相信django-channels是要走的路,儘管我不確定(從未使用它,但它很時尚)。