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.
Key Features
- Lightweight and modular
- Built-in development server and debugger
- RESTful request dispatching
- Jinja2 templating
- Support for secure cookies (sessions)
- Extensible with Flask extensions
Installation
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)
Routing
Define routes using @app.route()
decorator.
@app.route('/about')
def about():
return "About Page"
HTTP Methods
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')
Templates
Use Jinja2 templates to render HTML:
return render_template('index.html', name='Sai')
Example template:
<h1>Hello, {{ name }}!</h1>
Sessions & Cookies
Store data in sessions:
from flask import session
session['user'] = 'Sai'
Redirections & Reloads
from flask import redirect, url_for
return redirect(url_for('home'))
File Handling
Handle file uploads:
file = request.files['file']
file.save('uploads/' + file.filename)
Send emails using Flask-Mail extension.
Database (SQLAlchemy)
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)
Other Features
- Blueprints for modular apps
- Custom error pages
- RESTful APIs