Flask

Language: Python

Web

Flask was created by Armin Ronacher in 2010 as part of the Pocoo project. It was designed to provide a minimal yet extensible web framework that doesn’t force particular dependencies or structure. Flask emphasizes simplicity, readability, and freedom of choice, making it a popular choice for web apps, APIs, and rapid prototyping.

Flask is a lightweight and micro web framework for Python, ideal for building small to medium-sized web applications and APIs. It provides the essential tools for web development without imposing a specific project structure, giving developers flexibility and simplicity.

Installation

pip: pip install flask
conda: conda install flask

Usage

Flask allows you to define routes, request handlers, templates, and more. It supports RESTful routing, URL parameters, sessions, cookies, and templating via Jinja2. You can build APIs, web services, or full-fledged web applications with ease.

Simple Hello World App

from flask import Flask
app = Flask(__name__)

@app.get('/')
def home():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)

This example creates a basic Flask app with a single route `/`. Running this file starts a local server on port 5000 with debug mode enabled.

Using URL Parameters

from flask import Flask
app = Flask(__name__)

@app.get('/user/<username>')
def greet_user(username):
    return f'Hello, {username}!'

app.run(debug=True)

Flask supports dynamic URL parameters. Here, `<username>` is captured from the URL and passed to the `greet_user` function.

JSON Responses

from flask import Flask, jsonify
app = Flask(__name__)

@app.get('/data')
def data():
    return jsonify({'name': 'Flask', 'type': 'web framework'})

app.run(debug=True)

Use `jsonify` to return JSON responses, suitable for building APIs.

Handling POST Requests

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.post('/submit')
def submit():
    data = request.json
    return jsonify({'received': data})

app.run(debug=True)

Handle POST requests and access JSON data from `request.json`.

Using Templates

from flask import Flask, render_template
app = Flask(__name__)

@app.get('/')
def home():
    return render_template('index.html', title='Welcome')

app.run(debug=True)

Flask integrates with Jinja2 templates. `render_template` renders HTML templates with variables.

Error Handling

404 Not Found: Use `@app.errorhandler(404)` to define a custom handler for missing routes.
500 Internal Server Error: Use `@app.errorhandler(500)` to catch unhandled exceptions and log them.

Best Practices

Organize your app into blueprints for modularity.

Use environment variables for configuration (Flask config object).

Enable debug mode only in development.

Validate user inputs to prevent injection attacks.

Use Flask extensions for added functionality (Flask-Login, Flask-Migrate, etc.).