0

I am writing attempting to write website using python and flask. The website is to test peoples knowledge of NBA player stats. The website will show two players and then a random category. The person can then guess which player has the higher stat in that category. If the guess is correct than they get a point.

Currently my python code looks like this:

from flask import Flask, render_template, request

app = Flask(__name__)


from bs4 import BeautifulSoup
import requests
import random
import os
import time
url = 'https://hashtagbasketball.com/fantasy-basketball-rankings'
data = requests.get(url).text
soup = BeautifulSoup(data, 'html.parser')
table = soup.find("table", attrs={"class": "table--statistics"})
table_data = table.find_all('tr')
first = table_data[0]
column = first.find_all('a')

players = []


for row in table_data[1:]:
    name = row.find_all('a')
    stat = row.find_all('span', id=True)
    for x in name:
        player = []
        player.append(x.text)
        player.append(stat[0].text)
        player.append(stat[1].text)
        player.append(stat[2].text)
        player.append(stat[3].text)
        player.append(stat[4].text)
        player.append(stat[5].text)
        player.append(stat[6].text)
        player.append(stat[7].text)
        player.append(stat[8].text)         
        players.append(player)

allx = []

class Player:
  def __init__(self,players):
    self.name = players[0]
    self.field_goal_percentage = players[1]
    self.free_throw_percentage = players[2]
    self.three_points_made = players[3]
    self.points = players[4]
    self.rebounds = players[5]
    self.assist = players[6]
    self.steals = players[7]
    self.blocks = players[8]
    self.turnovers = players[9]


n = 0
while n<len(players):
  a = Player(players[n])
  allx.append(a)
  n += 1

score = 0

def add():
    global score
    score +=1


@app.route("/", methods=['GET','POST'])
def hello_world():
    playerx = random.sample(allx,2)
    player1 = playerx[0]
    player1_name = player1.name
    player2 = playerx[1]
    player2_name = player2.name

    categories = ['field_goal_percentage','free_throw_percentage','points','rebounds','steals','assist','blocks','turnovers','three_points_made']
    category_choice = categories[random.randint(0,(len(categories)-1))]
    category_choice_text = category_choice.replace('_',' ').capitalize()
    compare1 = getattr(player1,category_choice)
    compare2 = getattr(player2,category_choice)
    if float(compare1)>float(compare2):
        answer = 'a'
    else:
        answer ='b'

    if request.method == "POST":
        add()

    return render_template('home.html', player1=player1_name, player2=player2_name, category=category_choice_text, score = score, compare1=compare1, compare2=compare2, answer=answer)
    

if __name__ == '__main__':
    app.run(debug=True)

In the first section it is collecting all the top 200 players data from a website and storing it in a class called Player. Then in the @app.route part it is randomising two players and a stat.

The HTML code looks like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>NBA Stats Quiz</title>

<style>
* {
  box-sizing: border-box;
}

/* Create two equal columns that floats next to each other */
.column {
  float: left;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}
</style>
</head>
<body>
    <h1 style="text-align:center;font-size:60px"> NBA Stats Quiz</h1>
    <h1 style="text-align:center;font-size:30px"> Which player's stat is higher?</h1>
    <h1 style="text-align:center;font-size:30px"> Category: {{category}}</h1>
    <div class="row">
    <div class="column" style="text-align:center;width: 45%">
            <form method="post" >
            <h1><button style="font-size: 25px" value = 'POST'>{{player1}}</button>{{compare1}}{{answer}}</h1>
            </form>
            <img src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/Ja_Morant_2021.jpg/800px-Ja_Morant_2021.jpg' style="height:300px"></img>
    </div>
    <div class = 'column' style="text-align:center;width:10%">
        <h1>VS</h1><br><br><br><br><br><br>
        <h4>Current score</h4>
        <h4>{{score}}</h4>
    </div>
    <div class="column" style="text-align:center;width:45%">
          <form method="post" >
        <h1><button style="font-size: 25px" name = 'b'>{{player2}}</button>{{compare2}}</h1>
    </form>
        <img src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/Ja_Morant_2021.jpg/800px-Ja_Morant_2021.jpg' style="height:300px"></img>
    </div>
    
    </div> 

</body>
</html>

I'm sure the code is very messy on both parts but I just want to be able to click either of the buttons and then it checks to see if that value was the higher stat and if it is it will add 1 to the score and refresh the website to give another question. How would I go about doing this?

Thanks

I had managed to get a code (slightly different to the one above) that worked except it checked your click against the answers of the next question not the actual question that was displayed. So out-of-sync, from my understanding it was refreshing the page and thus the players/stats before checking to see if your click was correct.

  • Your script connect to hashtagbasketball.com everytime it needs the data, if a lot of user use your script, your server will send tonnes of request to the website, i wouldn't recommend this design because your server might get blocked by the website for sending too much request. Either create cache (update data only every few minute/hour), or use offline data which you update manually. – LLL Apr 12 '23 at 05:52
  • You can put the player stat as hidden input in the form which then get submitted when the user click the button. Good example is https://stackoverflow.com/questions/50891560/how-to-read-hidden-form-data-in-flask-function . The server then compare the submitted stat to see which one is bigger, and do action depending on whether the user is correct or not. However this can be hacked because the data is stored on user side. If you want the data to not get hacked, then you can store it in server side using database system (mysql, nosql, ect). – LLL Apr 12 '23 at 06:02

0 Answers0