Introduction to Flask Web Framework in Python


Flask: Python Web Framework

Flask is a lightweight, easy-to-use web framework for Python that enables you to build web applications quickly and with minimal boilerplate. It's known as a micro-framework because it doesn't come with built-in tools like form validation or database abstraction — but it gives you the flexibility to plug in extensions as needed.

Why Use Flask?

  • Simple & Lightweight: Minimalist design makes it easy to start.
  • Flexible & Extensible: Add only what you need.
  • RESTful Request Handling: Easily build REST APIs.
  • Wide Community Support: Tons of tutorials, extensions, and examples.
  • Built-in Development Server: Test apps locally without external servers.

Installing Flask

Before starting, install Flask using pip:

pip install Flask

Hello World in Flask

Here's how to create your first Flask web app:

from flask import Flask

# Create a Flask app instance
app = Flask(__name__)

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

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

Output:

Run the script:

python app.py

Visit http://127.0.0.1:5000 in your browser. You'll see:

Hello, Flask!

Flask Routes and Views

Routes define the URLs that users can access.

@app.route('/about')
def about():
    return 'This is the About page'

Visit http://127.0.0.1:5000/about → you'll see:

This is the About page

Handling HTTP Methods

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return 'Logging in...'
    else:
        return 'Login form'

HTML Templates with Jinja2

Create a folder called templates and add index.html:

templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Flask Template</title>
</head>
<body>
    <h1>Welcome, {{ name }}!</h1>
</body>
</html>

Flask Code:

from flask import render_template

@app.route('/hello/<name>')
def hello(name):
    return render_template('index.html', name=name)

Flask Forms and Input

from flask import request

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f'Hello, {name}!'

Form in HTML:

<form method="post" action="/submit">
    <input name="name">
    <button type="submit">Submit</button>
</form>

Flask Extensions (Examples)

  • Flask-SQLAlchemy: for databases
  • Flask-WTF: for form handling
  • Flask-Login: for user sessions

Flask Directory Structure (Best Practice)

/myapp
│
├── app.py
├── /templates
│   └── index.html
├── /static
│   └── style.css

Real-World Uses of Flask

  • REST APIs
  • Single-page applications (SPAs)
  • Admin panels and dashboards
  • Machine learning model interfaces
  • Lightweight content management systems