Flask in Python
1. What is Flask?
Flask is a lightweight Python web framework used to build web applications and web APIs.
It is written in Python and is based on Werkzeug for the web server/toolkit and Jinja for HTML templating.
In simple words:
Flask helps us create websites and APIs using Python.
For example, with Flask you can create:
- Websites
- REST APIs
- Login systems
- Admin panels
- Backend services
- CRUD applications
- Web applications
- Machine-learning model APIs
- Small and medium-sized backend applications
2. Why Do We Need Flask?
Normally, Python itself doesn't provide everything required to create a complete web application.
For example, a web application needs to handle:
Browser ↓ HTTP Request ↓ Python Web Application ↓ Process Request ↓ HTTP Response ↓ Browser
Flask provides tools to handle this process.
3. What is a Web Framework?
A web framework is a collection of tools and rules that helps developers build web applications.
Examples of Python web frameworks:
| Framework | Description |
|---|---|
| Flask | Lightweight and flexible |
| Django | Large, full-featured framework |
| FastAPI | Modern framework mainly used for APIs |
| Pyramid | Flexible Python web framework |
Flask is often chosen when you want to start with a simple application and add features as needed.
4. Main Features of Flask
Important Flask features include:
- Routing
- HTTP request handling
- HTTP response handling
- Templates
- Jinja2 template engine
- Static files
- Forms
- Cookies and sessions
- JSON responses
- REST APIs
- Error handling
- Blueprints
- Database integration
- Extensions
- Debugging and development server
5. Installing Flask
First check Python:
python --version
On Windows, you may also use:
py --version
Create a virtual environment:
python -m venv venv
Activate it.
Windows CMD
venv\Scripts\activate
Windows PowerShell
venv\Scripts\Activate.ps1
Linux/macOS
source venv/bin/activate
Install Flask:
pip install flask
Check installation:
pip show flask
6. Your First Flask Application
Create a file:
app.py
Write:
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, Flask!" if __name__ == "__main__": app.run(debug=True)
Run:
python app.py
Flask will start a development server, typically at:
http://127.0.0.1:5000
Open it in your browser.
You will see:
Hello, Flask!
7. Understanding the Code
Let's understand each line.
Import Flask
from flask import Flask
Imports the Flask class.
Create Flask application
app = Flask(__name__)
Creates the Flask application object.
__name__ tells Flask where the current application/module is located.
Create a route
@app.route("/")
This tells Flask:
When the user visits
/, execute the function below it.
Function
def home(): return "Hello, Flask!"
This function handles the request and returns the response.
Start server
if __name__ == "__main__": app.run(debug=True)
This starts the Flask development server when you directly run the file.
8. What is a Route?
A route connects a URL to a Python function.
Example:
@app.route("/about") def about(): return "About Page"
Now:
http://127.0.0.1:5000/about
will execute:
about()
9. Multiple Routes
A Flask application can have many routes.
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Home Page" @app.route("/about") def about(): return "About Page" @app.route("/contact") def contact(): return "Contact Page" if __name__ == "__main__": app.run(debug=True)
Routes:
/ → Home /about → About /contact → Contact
10. HTTP Methods
Web applications use HTTP methods to communicate between clients and servers.
Common methods:
| Method | Purpose |
|---|---|
| GET | Get/read data |
| POST | Send/create data |
| PUT | Update data |
| PATCH | Partially update data |
| DELETE | Delete data |
By default, a Flask route accepts GET.
@app.route("/users") def users(): return "Users"
11. GET Request
@app.route("/hello") def hello(): return "Hello User"
Visiting:
/hello
sends a GET request.
12. POST Request
To accept POST:
@app.route("/login", methods=["POST"]) def login(): return "Login request received"
Now the route accepts POST requests.
13. Multiple HTTP Methods
@app.route("/user", methods=["GET", "POST"]) def user(): return "User"
This route accepts both:
GET POST
14. URL Parameters
You can put a variable inside the URL.
@app.route("/user/<name>") def user(name): return f"Hello {name}"
If the user visits:
/user/Uday
Output:
Hello Uday
Here:
<name>
is a URL parameter.
15. Integer URL Parameter
Flask supports converters.
@app.route("/user/<int:id>") def user(id): return f"User ID: {id}"
Example:
/user/101
Output:
User ID: 101
Other common converters:
<int:value> <float:value> <string:value> <path:value> <uuid:value>
16. Query Parameters
A query parameter appears after ?.
Example:
/search?name=python
Use request.args.
from flask import Flask, request app = Flask(__name__) @app.route("/search") def search(): name = request.args.get("name") return f"You searched for {name}" if __name__ == "__main__": app.run(debug=True)
URL:
/search?name=python
Output:
You searched for python
17. Request Object
Flask provides the request object to access incoming request data.
from flask import request
It can provide information such as:
- Query parameters
- Form data
- JSON data
- HTTP method
- Headers
- Cookies
- Files
Example:
@app.route("/info") def info(): return request.method
18. HTML Pages with Flask
Flask can return HTML directly.
@app.route("/") def home(): return "<h1>Welcome to Flask</h1>"
But writing large HTML inside Python isn't convenient.
Instead, Flask uses templates.
19. Templates
Flask normally uses Jinja as its template engine.
Create:
project/ │ ├── app.py │ └── templates/ └── index.html
index.html:
<!DOCTYPE html> <html> <head> <title>Flask App</title> </head> <body> <h1>Welcome to Flask</h1> </body> </html>
Python:
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)
20. Passing Data to HTML
Python:
@app.route("/") def home(): name = "Uday" return render_template("index.html", name=name)
HTML:
<h1>Hello {{ name }}</h1>
Output:
Hello Uday
{{ }} is used to display values in Jinja templates.
21. Jinja Variables
Example:
<h1>{{ name }}</h1> <p>{{ age }}</p>
Python:
return render_template( "index.html", name="Uday", age=21 )
22. Jinja Conditions
You can use conditions inside templates.
{% if age >= 18 %} <p>You are an adult.</p> {% else %} <p>You are a minor.</p> {% endif %}
Jinja uses:
{{ }} → Display value {% %} → Logic/control {# #} → Comment
23. Jinja Loops
Python:
@app.route("/") def home(): students = ["Ram", "Shyam", "Hari"] return render_template( "index.html", students=students )
HTML:
<ul> {% for student in students %} <li>{{ student }}</li> {% endfor %} </ul>
Output:
Ram Shyam Hari
24. Static Files
Websites normally need:
- CSS
- JavaScript
- Images
Flask commonly stores these inside:
static/
Example:
project/ │ ├── app.py │ ├── templates/ │ └── index.html │ └── static/ ├── css/ │ └── style.css ├── js/ │ └── script.js └── images/ └── logo.png
In HTML:
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" >
25. url_for()
url_for() generates URLs for Flask routes or static files.
Example:
@app.route("/about") def about(): return "About"
HTML:
<a href="{{ url_for('about') }}">About</a>
Instead of manually writing:
<a href="/about">About</a>
Using url_for() makes URL management easier.
26. Forms
Flask can process HTML forms.
HTML:
<form method="POST"> <input type="text" name="username"> <button type="submit"> Submit </button> </form>
Python:
from flask import request @app.route("/form", methods=["GET", "POST"]) def form(): if request.method == "POST": username = request.form.get("username") return f"Hello {username}" return render_template("form.html")
27. JSON Data
Flask can receive JSON data.
Example request:
{ "name": "Uday", "age": 21 }
Python:
from flask import request @app.route("/data", methods=["POST"]) def data(): data = request.get_json() return data
28. Creating a JSON API
Flask can be used to create APIs.
from flask import Flask, jsonify app = Flask(__name__) @app.route("/api/student") def student(): data = { "name": "Uday", "course": "CSE", "semester": 6 } return jsonify(data) if __name__ == "__main__": app.run(debug=True)
Response:
{ "course": "CSE", "name": "Uday", "semester": 6 }
29. REST API
Flask is commonly used for REST APIs.
For example:
GET /api/students POST /api/students GET /api/students/1 PUT /api/students/1 DELETE /api/students/1
This is commonly used when a frontend communicates with a backend.
For example:
React / Next.js ↓ API ↓ Flask ↓ Database
30. Redirect
Flask can redirect users to another route.
from flask import redirect, url_for @app.route("/old") def old(): return redirect(url_for("home"))
Visiting:
/old
redirects to:
/
31. Sessions
Flask provides sessions for storing user-specific information between requests.
Example:
from flask import Flask, session app = Flask(__name__) app.secret_key = "your-secret-key" @app.route("/login") def login(): session["username"] = "Uday" return "Logged in"
Retrieve it:
@app.route("/profile") def profile(): username = session.get("username") return f"Welcome {username}"
Sessions are commonly used for:
- Login systems
- User preferences
- Temporary user data
- Authentication state
For real applications, the secret key should be kept securely rather than hard-coded in source code.
32. Cookies
Flask can read and set cookies.
from flask import make_response @app.route("/set") def set_cookie(): response = make_response("Cookie set") response.set_cookie("username", "Uday") return response
Read:
from flask import request @app.route("/get") def get_cookie(): username = request.cookies.get("username") return username
33. Error Handling
Flask allows custom error pages.
Example:
@app.errorhandler(404) def page_not_found(error): return "Page not found", 404
For 500:
@app.errorhandler(500) def server_error(error): return "Internal server error", 500
Common HTTP status codes:
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
34. Database with Flask
Flask itself does not force you to use one particular database.
You can use:
- SQLite
- MySQL
- PostgreSQL
- MongoDB
- Other databases
A common approach is using an ORM such as SQLAlchemy.
Typical architecture:
User ↓ Flask Route ↓ Business Logic ↓ SQLAlchemy ↓ Database
35. CRUD Application
CRUD means:
C → Create R → Read U → Update D → Delete
For example, a student management system:
POST /students → Create GET /students → Read PUT /students/1 → Update DELETE /students/1 → Delete
This is one of the most common Flask project patterns.
36. Blueprints
As an application becomes larger, putting everything in app.py becomes difficult.
Flask provides Blueprints to organize routes into separate modules.
Example:
project/ │ ├── app.py │ ├── routes/ │ ├── auth.py │ ├── users.py │ └── products.py │ └── templates/
For example:
from flask import Blueprint users = Blueprint("users", __name__) @users.route("/users") def users_page(): return "Users"
Then register it:
app.register_blueprint(users)
Blueprints are useful for larger applications.
37. Flask Project Structure
A small project:
myproject/ │ ├── app.py │ ├── templates/ │ ├── index.html │ └── about.html │ └── static/ ├── css/ │ └── style.css └── js/ └── script.js
A larger project may look like:
myproject/ │ ├── app/ │ ├── __init__.py │ ├── routes/ │ │ ├── auth.py │ │ ├── users.py │ │ └── products.py │ │ │ ├── models/ │ │ └── user.py │ │ │ ├── templates/ │ └── static/ │ ├── tests/ │ ├── config.py ├── requirements.txt └── run.py
The exact structure depends on the project.
38. Flask Extensions
Flask follows a minimal/core approach, so additional functionality is commonly added through extensions.
Examples:
| Extension | Purpose |
|---|---|
| Flask-SQLAlchemy | SQLAlchemy integration |
| Flask-Migrate | Database migrations |
| Flask-Login | User login management |
| Flask-WTF | Forms and validation |
| Flask-CORS | Cross-Origin Resource Sharing |
| Flask-Mail | Email functionality |
| Flask-JWT-Extended | JWT authentication |
Extensions can be installed using pip.
Example:
pip install flask-sqlalchemy
39. Debug Mode
During development:
app.run(debug=True)
Debug mode provides useful development features such as automatic reloading and detailed error information.
Do not use development debug mode as the production deployment configuration.
40. Development Server vs Production
The server started by:
app.run()
is intended for development/testing.
For production, Flask applications are normally run behind a production WSGI server such as:
Gunicorn
A common deployment architecture is:
Internet ↓ Nginx ↓ Gunicorn ↓ Flask ↓ Database
On Windows, other production deployment approaches are commonly used depending on the environment.
41. Flask Application Flow
A typical Flask request works like this:
Browser | | HTTP Request ↓ Flask App | ↓ Routing | ↓ View Function | ↓ Business Logic | +----+----+ | | ↓ ↓ Database Other API | ↓ Result | ↓ HTTP Response | ↓ Browser
42. Complete Small Flask Website
app.py
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): return render_template("index.html") @app.route("/about") def about(): return render_template("about.html") if __name__ == "__main__": app.run(debug=True)
templates/index.html
<!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h1>Welcome to My Flask Website</h1> <a href="{{ url_for('about') }}"> About </a> </body> </html>
templates/about.html
<!DOCTYPE html> <html> <head> <title>About</title> </head> <body> <h1>About Us</h1> <a href="{{ url_for('home') }}"> Home </a> </body> </html>
Project:
myproject/ │ ├── app.py │ └── templates/ ├── index.html └── about.html
43. Flask vs Django
| Flask | Django |
|---|---|
| Lightweight | Full-featured |
| Minimal core | Many built-in features |
| Flexible structure | More structured |
| Easy to start | Larger learning curve |
| Extensions add features | Many features included |
| Good for APIs and smaller apps | Good for large full-featured applications |
Neither is universally suitable for every project; the choice depends on application requirements.
44. Flask vs FastAPI
| Flask | FastAPI |
|---|---|
| General-purpose web framework | API-focused modern framework |
| Very mature ecosystem | Modern type-hint-based approach |
| Jinja templates available | Usually used for APIs |
| Simple routing | Automatic API documentation |
| WSGI-based traditional architecture | ASGI-based |
| Flexible | Strong focus on API development |
45. Advantages of Flask
1. Simple
The basic application can be very small.
2. Lightweight
Flask's core doesn't force many components on you.
3. Flexible
You can choose your database, authentication system, project structure, and extensions.
4. Python-based
You can use Python libraries and Python programming concepts.
5. Good for APIs
Flask can easily return JSON responses.
6. Good for Learning
It helps beginners understand:
Request ↓ Route ↓ Function ↓ Response
46. Disadvantages / Considerations
1. You Need to Choose More Components
For a larger application, you may need to select extensions for databases, authentication, forms, etc.
2. Large Applications Need Organization
A large Flask project needs a good architecture using things such as:
- Blueprints
- Application factories
- Service layers
- Models
- Configuration management
3. Security Is Not Automatically Solved
You still need to correctly implement:
- Authentication
- Authorization
- Input validation
- CSRF protection where applicable
- Secure sessions
- Password hashing
- Secure configuration
47. Flask and Frontend
Flask can serve HTML itself:
Flask ↓ Jinja ↓ HTML/CSS/JavaScript
Or Flask can act only as an API backend:
React / Next.js ↓ API ↓ Flask ↓ Database
This second approach is very common for separate frontend/backend applications.
48. Flask Learning Roadmap
Since you are learning Python, a good Flask sequence is:
Python Basics ↓ Functions ↓ Modules & Packages ↓ Virtual Environment ↓ HTTP Basics ↓ Flask Installation ↓ First Flask App ↓ Routes ↓ HTTP Methods ↓ Request & Response ↓ Templates / Jinja ↓ Forms ↓ Static Files ↓ JSON ↓ REST API ↓ Database ↓ CRUD ↓ Authentication ↓ Blueprints ↓ Error Handling ↓ Testing ↓ Deployment
49. Important Flask Terms
| Term | Meaning |
|---|---|
| Flask | Python web framework |
| Application | Flask web application |
| Route | URL mapped to a function |
| View function | Function that handles a request |
| Request | Data sent from client to server |
| Response | Data sent from server to client |
| Jinja | Template engine |
| Template | HTML file with dynamic content |
| Static files | CSS, JS, images |
| Session | Stores user-specific data between requests |
| Blueprint | Organizes application components |
| API | Interface for software communication |
| JSON | Common data format for APIs |
| Extension | Adds functionality to Flask |
In one line:
Flask is a lightweight Python web framework that allows you to build web applications and APIs by handling routes, requests, responses, templates, databases, authentication, and other web functionality.