[英]Random match-up with Python and Google App Engine
我正在建立一個網站,從數據庫中隨機選擇兩個音樂視頻,並進行直接投票。 我需要一種算法,該算法將繼續為用戶選擇唯一的匹配,但不包括他們過去的匹配,而是替換視頻以創建新的匹配。 您可以在此處查看頁面示例: http : //10.showtownmvp.appspot.com/
我正在Google App Engine-Python上運行此程序,並具有一個投票表和視頻表來存儲結果。 我想盡可能地保持隨機性,並避免多次查詢,因此,如果您對如何在NDB中進行建模有什么建議或有一個好的算法,我將不勝感激!
我針對此問題的解決方案是查詢數據存儲區中的所有視頻並隨機選擇一個。 我還對用戶的過去投票/對決進行了查詢,並將其轉換為列表,這樣我就可以在不運行多個查詢的情況下進行操作。 使用隨機視頻,我使用了while循環來查找不在上一個比賽列表中的第二個視頻。 如果未找到視頻,則程序將從視頻列表中刪除隨機選擇,然后選擇一個新樣本並再次運行搜索。 代碼如下:
class MainHandler(views.Template):
def post(self):
# NOTE: we are posting genre and state.
user = self.user_check()
self.videos = models.videos.Videos.fetch_featured()
try:
random.sample(self.videos,2)
if user:
self.user_votes = models.voting.Voting.query_by_user(user.key)
if self.user_votes != None:
self.user_votes = [[x.video_one,x.video_two] for x in self.user_votes]
page_vids = False
while page_vids == False and len(self.videos)>1:
rand_vid = random.choice(self.videos)
page_vids = self.find_match(rand_vid)
self.videos.remove(rand_vid)
else:
page_vids = random.sample(self.videos,2)
else:
page_vids = random.sample(self.videos,2)
except:
page_vids = None
def find_match(self, rand_vid):
i =0
while i < len(self.videos):
if rand_vid.key != self.videos[i].key and ([rand_vid.key,self.videos[i].key] not in self.user_votes and [self.videos[i].key, rand_vid.key] not in self.user_votes):
return [rand_vid,self.videos[i]]
i+=1
return False
class Videos(ndb.Model):
acc_key = ndb.KeyProperty()
musician_key = ndb.KeyProperty()
musician_name = ndb.StringProperty()
embed_link = ndb.StringProperty()
genre_tag = ndb.StringProperty()
video_title = ndb.StringProperty()
featured = ndb.BooleanProperty(default = False)
likes_count = ndb.IntegerProperty()
video_added = ndb.DateTimeProperty(auto_now_add = True)
@classmethod
def query_by_account(cls, acc_key):
return cls.query(cls.acc_key == acc_key).fetch()
@classmethod
def fetch_featured(cls):
return cls.query(cls.featured == True).fetch(100)
class Voting(ndb.Model):
voter_acc_key = ndb.KeyProperty()
voter_type = ndb.StringProperty()
video_one = ndb.KeyProperty()
video_one_artist_key = ndb.KeyProperty()
video_two = ndb.KeyProperty()
video_two_artist_key = ndb.KeyProperty()
voter_choice = ndb.KeyProperty()
video_set_check = ndb.KeyProperty(repeated = True)
voter_ip = ndb.StringProperty()
vote_time = ndb.DateTimeProperty(auto_now_add = True)
@classmethod
def query_by_user(cls, acc_key):
return cls.query(cls.voter_acc_key == acc_key).fetch(2000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.