Introduction to Flask

Flask is a lightweight WSGI web application framework in Python. It is designed with simplicity and flexibility in mind, making it easy to get started with web development.

pip install flask

Create a simple app:

from flask import Flask
app = Flask(__name__)
@app.route('/') def home(): return "Hello, Flask!"
if __name__ == '__main__': app.run(debug=True)

Define routes using @app.route() decorator.

@app.route('/about')
def about():
return "About Page"

Handle different HTTP methods (GET, POST, etc.):

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# process login
pass
return render_template('login.html')

Use Jinja2 templates to render HTML:

return render_template('index.html', name='Sai')

Example template:

<h1>Hello, {{ name }}!</h1>

Store data in sessions:

from flask import session
session['user'] = 'Sai'
from flask import redirect, url_for
return redirect(url_for('home'))

Handle file uploads:

file = request.files['file']
file.save('uploads/' + file.filename)

Send emails using Flask-Mail extension.

Use SQLAlchemy for ORM:

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)