Building A Basic Web App With Flask


title: Building a Basic Web App with Flask author: PythonTimes.com date: Today’s Date


Building A Basic Web App With Flask
Building A Basic Web App With Flask

Introduction

Flask is a micro web framework for Python, which is great for both beginners and experienced developers due to its simplicity and scalability. In this tutorial, we’ll guide you step by step on building your own basic web app using Flask.

This article assumes familiarity with Python. If you are new to Python, consider catching up on some basics before proceeding with this article.

Understanding What Flask Is

Flask is a web framework, a set of tools to build web applications. It’s Python’s lightest, most flexible and easy-to-use tool for this purpose. Despite its simplicity, Flask is incredibly powerful, and it can be used to build just about anything, from static websites to complex APIs.

To make things even easier, Flask uses Jinja2 for templates and Werkzeug for handling lower-level routing, among others.

Setting Up Your Environment

First things first, we need to set up our environment for development. Python 3.5 or higher is required for Flask.

We recommend setting up a virtual environment for Flask projects. This separates the Python and Flask installation from the system’s Python interpreter and keeps any dependencies separated as well.

To install the virtual environment, open your terminal and type:

pip install virtualenv

Then, create a new directory for your project, navigate into it, and create a new virtual environment:

mkdir myflaskapp
cd myflaskapp
virtualenv venv

Activate the environment by typing:

On Windows:

venv\Scripts\activate

On Unix or MacOS:

source venv/bin/activate

Next, install Flask:

pip install flask

Now, you are ready to start developing your Flask application!

Creating Your First Flask App

In your project directory, create a new file named app.py and open it in your text editor. Add the following lines of code:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

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

To understand this piece of code:

  • from flask import Flask imports the Flask module and allows us to create a web application.
  • app = Flask(__name__) creates an instance of the Flask class for our application.
  • @app.route('/') is a decorator, telling Flask what URL should trigger the function home().
  • def home(): is the function that gets triggered at the root URL.
  • return "Hello, Flask!" is what the function returns. In this case, when we reach the root URL, it will return the string “Hello, Flask!”.
  • if __name__ == '__main__': checks if the script is being run directly. If it is, it runs the Flask development server.
  • app.run(debug=True) runs the application.

Running Your Flask App

Go back to your terminal, ensure your virtual environment is activated, and navigate to your project folder if you are not already there, then type:

python app.py

You should see the Flask development server start up:

* Running on http://localhost:5000/ (Press CTRL+C to quit)

Open your web browser and navigate to http://localhost:5000/. You should see “Hello, Flask!” displayed.

Building a Basic Web App

For our basic web app, we’ll create a simple page that generates a random number every time it is refreshed. We’ll use Python’s built-in random library.

Modify your app.py to look as follows:

from flask import Flask
import random

app = Flask(__name__)

@app.route('/')
def home():
    number = random.randint(1, 10)
    return "Your random number is " + str(number)

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

Refresh your browser to generate random numbers!

Templates

Up till now, we have been returning simple strings from our functions. While this can work, it’s not what Flask is truly designed for.

Flask uses a template engine called Jinja2 that allows us to build complex HTML pages with Python-like expressions.

You can create make a new directory called templates in your project folder and create a new file home.html. Write a simple HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Your random number is {{ number }}</h1>
</body>
</html>

In app.py, import the render_template function from Flask, and modify your home function to pass the random number to the template:

from flask import Flask, render_template
import random

app = Flask(__name__)

@app.route('/')
def home():
    number = random.randint(1, 10)
    return render_template('home.html', number=number)

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

Now, refreshing the browser will give you a randomly generated number within a proper HTML page.

Conclusion

Flask is an exceptionally strong and versatile web framework which allows programmers of all skill levels to create dynamic web applications quickly and efficiently. Its scalability and the fact it is written in Python, one of the world’s most popular programming languages, makes it an excellent choice for building web-based projects.

FAQ

  1. What is Flask?
    Flask is a simple web framework for Python.

  2. Why use Flask?
    Flask is lightweight, easy to use and it can suit projects of any size.

  3. What’s a decorator in Flask?
    A decorator in Flask allows you to hook custom functions into Flask’s request/response processing flow.

  4. What is the role of Jinja2 in Flask?
    Flask uses Jinja2 template engine that allows Python-like expressions to be used in HTML.

  5. What does if __name__ == '__main__': do?
    It checks if the script is running directly (not being imported), and if true, runs the Flask development server.

Share this article:

Leave a Comment