Technology • 2024-08-31
Python Flask Web Development: Beginner's Guide for Indian Developers
Learn Python Flask from scratch — build your first web app, API, and understand routing, templates, and database integration.
PythonFlaskWeb DevelopmentTechnology
⏱ 1 min read
What Is Flask?
Flask is a lightweight Python web framework — "micro" because it provides only the essentials and lets you add what you need. It's perfect for APIs, small web apps, and learning web development. Unlike Django (batteries included), Flask is simpler to understand. Widely used in Indian startups and data science projects.
Installation
pip install flask
# Create your first app: app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, India!'
if __name__ == '__main__':
app.run(debug=True)
Routing in Flask
@app.route('/about')
def about():
return 'About page'
# Dynamic routes
@app.route('/user/<username>')
def user_profile(username):
return f'Profile: {username}'
# HTTP methods
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Handle form submission
return 'Logged in'
return 'Login page'
HTML Templates with Jinja2
# templates/index.html
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {{ name }}!</h1>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</body>
</html>
# app.py
from flask import render_template
@app.route('/')
def home():
return render_template('index.html', name='Ravi', items=['a','b','c'])
Simple REST API
from flask import Flask, jsonify, request
app = Flask(__name__)
products = [{"id":1, "name":"Dosa", "price":60}, {"id":2, "name":"Idli", "price":40}]
@app.route('/api/products', methods=['GET'])
def get_products():
return jsonify(products)
@app.route('/api/products', methods=['POST'])
def add_product():
new = request.json
products.append(new)
return jsonify(new), 201
Connecting to SQLite Database
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(120), unique=True)