How to build a Flask BMI Calculator

flask bmi calculator bmi calculator

Body Mass Index – BMI, is a measure of a person’s weight in relation to their height and is used to determine if a person is underweight, normal weight, overweight, or obese. It is calculated by dividing a person’s weight in kilograms by their height in meters squared (kg/m^2). To know more about Body Mass Index, check this article on wikipedia

In this article, we will be building a flask app that calculates your BMI.

To begin we will install flask which will be our web server. To install flask run the command below.

pip3 install flask

Now let’s create a folder called bmi-calculator, inside the folder create a file called app.py

Inside the bmi-calculator create a folder called templates and insert a file called index.html.

Now inside the app.py let’s import the following modules.

from flask import Flask, render_template, request

Next we need to initialize our flask app. Insert the following in the app.py file.

app = Flask(__name__)

Now let’s create the function to handle the calculations. Inside the app.py file add the following

@app.route('/', methods=['GET', 'POST'])
def bmi_calculator():
    # set the initial BMI to 0
    bmi = 0

    if request.method == 'POST':
        weight = float(request.form['weight'])
        height = float(request.form['height'])

        # calculate the BMI
        bmi = weight / (height ** 2)

    return render_template("index.html", bmi=bmi)

The above function receives height and weight from the browser and then the bmi is calculated and the results are rendered to the browser.

Now let’s add the following in the app.py file.

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

Now let’s create our template. Insert the following in the index.html file that we created at the start.

<!doctype html>
<html>
  <head>
    <title>Flask BMI Calculator</title>
  </head>
  <body>
    <form method="post">
      <label for="weight">Weight (kg):</label>
      <input type="text" name="weight" id="weight">
      <br>
      <label for="height">Height (m):</label>
      <input type="text" name="height" id="height">
      <br>
      <input type="submit" value="Calculate BMI">
    </form>
    <p>BMI: {{ bmi }}</p>
  </body>
</html>

The above form accepts height and weight and then submits them to the server for calculations

Now run the server using the below command.

python3 app.py 

You can also use the below command.

flask run

Now your server should be up and running, open your browser and insert the following address.

http://127.0.0.1:5000

You should now see your web app pop up as shown below.

There you have it. Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *