2016-11-25 239 views
0

我有以下代碼。它工作正常,但當players列表長度變爲0時,我的網頁變空白,並且這個IndexError: list index out of range錯誤出現在我的終端(服務器)中。當players列表變空時,我想要一種方法將服務器重定向到self.redirect('/')IndexError:列表索引超出範圍| webapp2

def choose_random_player(list): 
    return random.choice(list) 


class GuessPlayer(Handler): 
    players = ['sanchez', 'welbeck', 'giroud', 'ozil', 'ramsey'] 
    random_player = choose_random_player(players) 
    score = 0 

    def get(self): 
     self.render("guessplayer.html", 
        random_player=GuessPlayer.random_player, 
        score=GuessPlayer.score) 

    def post(self): 
     user_answer = self.request.get("player-name") 
     if user_answer == GuessPlayer.random_player: 
      GuessPlayer.score += 1 
      GuessPlayer.players.remove(GuessPlayer.random_player) 
      GuessPlayer.random_player = choose_random_player(GuessPlayer.players) 
      self.render("guessplayer.html", 
         random_player=GuessPlayer.random_player, 
         score=GuessPlayer.score) 
     else: 
      self.render("guessplayer.html", 
         random_player=GuessPlayer.random_player, 
         score=GuessPlayer.score) 

HTML表單:

{% extends 'base.html' %} 

{% block content %} 

<div class="row"> 
    <div class="col-md-12 text-center"> 
     <h4>Enter The Player Name</h4> 
     <div class="thumbnail"> 
     <div class="score">Score: {{score}}</div> 
     <img src="../images/{{random_player}}.jpg" alt="..."> 
     <form method="post"> 
      <input type="text" name="player-name"> 
      <br><br> 
      <input type="submit" class="btn btn-primary"> 
     </form> 
     </div> 
    </div> 
</div> 

{% endblock %} 
+0

請加上'choose_random_player'的定義 –

回答

0

我猜測,當players是一個空列表,choose_random_player(players)引發IndexError

如果需要,您可以捕獲此異常並將用戶重定向到/,但這有點難看。

def get(self): 
    try: 
     random_player = choose_random_player(players) 
    except IndexError: 
     self.redirect('/') 

    self.render(...) 

一個更乾淨的版本將是檢查是否players是選擇隨機播放之前的空單。

def get(self): 
    if len(players) == 0: 
     self.redirect('/') 

    random_player = choose_random_player(players) 
    self.render(...) 

您必須在您的post處理程序中編寫類似的檢查。

+0

兩者都試過,仍然在什麼行上得到了錯誤 – hadyfarhat

+0

@ h236a? –

相關問題