2014-03-01 16 views
1

我有試圖從我的Flask應用程序中的數據庫中拉出一個「隨機」項目的問題。此功能只需要返回用戶最近未觀看的視頻。我現在不擔心多個用戶。我目前的做法不起作用。這是我在用的:如何從列表中選擇隨機但不近期的資產?

@app.route('/_new_video') 
def new_video(): 

這裏是我問的重要組成部分:

current_id = request.args.get('current_id') 
    video_id = random.choice(models.Video.query.all()) # return list of all video ids 
    while True: 
     if video_id != current_id: 
      new_video = models.Video.query.get(video_id) 

,然後我返回它:

  webm = new_video.get_webm() #returns filepath in a string 
      mp4 = new_video.get_mp4() #returns filepath in a string 
      return jsonify(webm=webm,mp4=mp4,video_id=video_id) 

隨機範圍開始爲1,因爲第一個資產已從數據庫中刪除,所以數字0不與id關聯。理想情況下,用戶不會收到他們最近觀看的視頻。

回答

1

我建議使用collections.deque來存儲最近觀看的列表。它會保存一個列表,比如項目集合,並且在添加到列表中時,如果達到其最大長度,它會自動刪除最早的項目,並按照先入先出的原則。

import collections 

這裏是一個生成器,您可以使用它來獲取最近未觀察過的隨機vid。 denom參數將允許您更改最近觀看列表的長度,因爲它用於確定recent_watched的最大長度,作爲vid列表的一小部分。

def gen_random_vid(vids, denom=2): 
    '''return a random vid id that hasn't been recently watched''' 
    recently_watched = collections.deque(maxlen=len(vids)//denom) 
    while True: 
     selection = random.choice(vids) 
     if selection not in recently_watched: 
      yield selection 
      recently_watched.append(selection) 

我將創建一個快速列表演示它:

vids = ['vid_' + c for c in 'abcdefghijkl'] 

而這裏的用法:

>>> recently_watched_generator = gen_random_vid(vids) 
>>> next(recently_watched_generator) 
'vid_e' 
>>> next(recently_watched_generator) 
'vid_f' 
>>> for _ in range(10): 
...  print(next(recently_watched_generator)) 
... 
vid_g 
vid_d 
vid_c 
vid_f 
vid_e 
vid_g 
vid_a 
vid_f 
vid_e 
vid_c 
+2

此功能被放置在一個單獨的文件從我的路線和進口。然後,我在程序的開頭初始化了生成器,並將其發送給我的路由功能。 像這樣: [隨機數發生器(https://github.com/djds23/deanstream/blob/master/app/randomizer.py) 轉到: [路由](https://github.com/ djds23/deanstream/blob/master/app/routes.py) 非常感謝Aaron! – djds23