Flask in Python – Full Course (Line by Line Explanation)

Flask is a lightweight and powerful web framework for Python that makes it easy to build web applications. It is designed to be simple, yet highly flexible, allowing developers to create anything from simple web pages to complex web applications.


1. Installing Flask

Flask is not included with Python by default, so you need to install it first.

Step 1: Install Flask

Run the following command in your terminal or command prompt:

  • pip install flask


Once installed, you can verify the installation by running:

  • python -c "import flask; print(flask.__version__)"



2. Creating a Simple Flask App

Now, let’s create a basic Flask application.

Step 2: Create a Flask Application

Create a new file called app.py and add the following code:

  • from flask import Flask


  • # Create an instance of Flask

  • app = Flask(__name__)


  • # Define a route

  • @app.route('/')

  • def home():

  •     return "Hello, Flask!"


  • # Run the application

  • if __name__ == '__main__':

  •     app.run(debug=True)


Explanation:

  1. We import Flask from the flask module.

  2. We create an instance of Flask (our web application).

  3. We define a route using @app.route('/'), which maps the home page (/) to the home() function.

  4. When someone visits the home page, Flask will return "Hello, Flask!".

  5. We use app.run(debug=True), which starts the development server and enables debugging.

Run the Application

Execute the script:

  • python app.py


You should see output like this:

  • Running on http://127.0.0.1:5000/


Open a web browser and visit http://127.0.0.1:5000/, and you should see:

  • Hello, Flask!



3. Routing in Flask

Flask allows defining multiple routes.

Modify app.py to add another route:

  • @app.route('/about')

  • def about():

  •     return "This is the About Page"


Now, when you visit http://127.0.0.1:5000/about, it will display:

  • This is the About Page


Dynamic Routes

We can also use dynamic routes:

  • @app.route('/user/<name>')

  • def user(name):

  •     return f"Hello, {name}!"


Now, visiting http://127.0.0.1:5000/user/John will display:

  • Hello, John!



4. Using HTML Templates in Flask

Instead of returning plain text, we can return HTML templates.

Step 1: Create a Templates Folder

Create a folder called templates in your project directory.

Inside the templates folder, create an index.html file:

  • <!DOCTYPE html>

  • <html>

  • <head>

  •     <title>Flask Webpage</title>

  • </head>

  • <body>

  •     <h1>Welcome to Flask</h1>

  • </body>

  • </html>


Step 2: Modify app.py to Use Templates

  • from flask import Flask, render_template


  • app = Flask(__name__)


  • @app.route('/')

  • def home():

  •     return render_template('index.html')


  • if __name__ == '__main__':

  •     app.run(debug=True)


  • The render_template('index.html') function looks for the index.html file in the templates directory and renders it in the browser.


5. Handling Forms in Flask

Step 1: Install Flask-WTF

To handle forms easily, install Flask-WTF:

  • pip install flask-wtf


Step 2: Create a Simple Form

Modify templates/index.html:

  • <form action="/submit" method="POST">

  •     <input type="text" name="username" placeholder="Enter your name">

  •     <input type="submit" value="Submit">

  • </form>


Step 3: Modify app.py to Handle Form Submission

  • from flask import Flask, render_template, request


  • app = Flask(__name__)


  • @app.route('/')

  • def home():

  •     return render_template('index.html')


  • @app.route('/submit', methods=['POST'])

  • def submit():

  •     username = request.form['username']

  •     return f"Hello, {username}!"


  • if __name__ == '__main__':

  •     app.run(debug=True)


  • The /submit route captures the username input from the form and returns a greeting.


6. Using Flask with Databases (SQLite)

Step 1: Install SQLite

SQLite comes pre-installed with Python, but install Flask-SQLAlchemy for easier database handling:

  • pip install flask-sqlalchemy


Step 2: Define the Database Model

Modify app.py:

  • from flask import Flask, render_template, request

  • from flask_sqlalchemy import SQLAlchemy


  • app = Flask(__name__)

  • app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'

  • db = SQLAlchemy(app)


  • # Define User Model

  • class User(db.Model):

  •     id = db.Column(db.Integer, primary_key=True)

  •     name = db.Column(db.String(80), nullable=False)


  • # Create Database Tables

  • with app.app_context():

  •     db.create_all()


  • @app.route('/')

  • def home():

  •     return render_template('index.html')


  • @app.route('/submit', methods=['POST'])

  • def submit():

  •     username = request.form['username']

  •     new_user = User(name=username)

  •     db.session.add(new_user)

  •     db.session.commit()

  •     return f"User {username} added to the database!"


  • if __name__ == '__main__':

  •     app.run(debug=True)


  • This script creates a database and stores submitted usernames in an SQLite database.


7. REST API in Flask

You can create an API using Flask’s jsonify method.

Modify app.py:

  • from flask import Flask, jsonify


  • app = Flask(__name__)


  • @app.route('/api/users')

  • def get_users():

  •     users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]

  •     return jsonify(users)


  • if __name__ == '__main__':

  •     app.run(debug=True)


Now, visiting http://127.0.0.1:5000/api/users will return:

  • [

  •     {"id": 1, "name": "Alice"},

  •     {"id": 2, "name": "Bob"}

  • ]



8. Running Flask in Production

For production, use Gunicorn:

  • pip install gunicorn

  • gunicorn -w 4 app:app


  • -w 4 means 4 worker processes.


9. Flask Authentication

To handle user authentication, install Flask-Login:

  • pip install flask-login


Then, implement login/logout routes and user sessions.


Conclusion

This is a complete guide to Flask covering: ✅ Installation
✅ Routing & Templates
✅ Forms Handling
✅ SQLite Database
✅ REST API
✅ Deployment

Would you like a detailed explanation of any specific section? 🚀