Introduction
Flask is a lightweight Python web framework. It’s perfect for building APIs, dashboards, small web apps, bots backend endpoints, or full CodeTweakrs tools. Simple, flexible, and fast.
1. Installing Flask
pip install flask
2. Basic Flask App
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
app.run()
Running the file starts a local server on http://127.0.0.1:5000.
3. Debug Mode (Auto Restart)
app.run(debug=True)
4. Returning HTML
@app.route("/dashboard")
def dash():
return "Dashboard Loaded
"
5. Returning JSON
from flask import jsonify
@app.route("/api/user")
def user():
return jsonify({"name": "Kaloyan", "rank": "Pro"})
6. URL Parameters
@app.route("/hello/<name>")
def hello(name):
return f"Hello {name}!"
7. Query Arguments
@app.route("/sum")
def summ():
from flask import request
a = int(request.args.get("a", 0))
b = int(request.args.get("b", 0))
return str(a + b)
8. Handling POST Requests
@app.route("/login", methods=["POST"])
def login():
from flask import request
data = request.json
return {"status": "ok", "user": data.get("name")}
9. Templates (HTML Files)
Inside /templates/home.html:
<h1>Welcome, {{ user }}</h1>
Use it in Flask:
from flask import render_template
@app.route("/profile")
def profile():
return render_template("home.html", user="Kaloyan")
10. Static Files (CSS/JS)
Create a /static folder.
<link rel="stylesheet" href="/static/style.css">
11. Structuring a Real Flask App
/project
/static
/templates
app.py
12. Redirects
from flask import redirect
@app.route("/old")
def old():
return redirect("/new")
13. Sessions (Login Cookies)
from flask import session
app.secret_key = "secret123"
session["user"] = "Kaloyan"
14. Error Handlers
@app.errorhandler(404)
def nf(e):
return "Page not found", 404
15. Deploying Flask (Gunicorn + Nginx)
pip install gunicorn
gunicorn app:app
Use Nginx as reverse proxy in production.
Summary
- Flask is simple but powerful
- Perfect for APIs, dashboards, lightweight web apps
- Supports routing, templates, JSON, POST, redirects
- Easy file structure: templates + static folders
- Production uses Gunicorn + Nginx