DEV Community

Cover image for Flask: A Comprehensive Guide
Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on • Edited on

4 1 1 1 1

Flask: A Comprehensive Guide

Introduction

Flask is a micro web framework for Python, designed to be lightweight and modular while still offering the flexibility needed to build robust web applications. It is widely used for its simplicity, scalability, and extensive community support. This guide will take you from the very basics of Flask to advanced features, ensuring a solid understanding of the framework.

Read Flask with Examples


1. What is Flask?

Flask is a web framework for Python that provides tools, libraries, and technologies for building web applications. Unlike Django, which is a full-fledged web framework with built-in features, Flask follows a minimalistic approach, allowing developers to choose their tools as needed.

Features of Flask:

  • Lightweight & Simple: Does not come with built-in ORM, authentication, or admin panel.
  • Modular: Allows integration of extensions as per project needs.
  • Flexible: Supports RESTful API development.
  • Jinja2 Templating: Provides powerful templating for rendering dynamic HTML pages.
  • WSGI-based: Uses Werkzeug, a WSGI toolkit for request handling.

2. Setting Up Flask

Installation

To get started, install Flask using pip:

pip install flask
Enter fullscreen mode Exit fullscreen mode

Creating a Simple Flask Application

Create a Python file, e.g., app.py, and write the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Running the Flask App

python app.py
Enter fullscreen mode Exit fullscreen mode

Navigate to http://127.0.0.1:5000/ in your browser to see the output.


3. Routing in Flask

Flask provides routing functionality to map URLs to functions.

@app.route('/about')
def about():
    return "This is the about page."
Enter fullscreen mode Exit fullscreen mode

Dynamic Routing

@app.route('/user/<string:name>')
def greet(name):
    return f"Hello, {name}!"
Enter fullscreen mode Exit fullscreen mode

URL Converters in Flask

Flask allows type-specific URL converters:

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f"Post ID: {post_id}"
Enter fullscreen mode Exit fullscreen mode

Using Multiple Routes

@app.route('/contact')
@app.route('/support')
def contact():
    return "Contact us at support@example.com"
Enter fullscreen mode Exit fullscreen mode

4. Flask Templates with Jinja2

Flask uses Jinja2 for rendering dynamic content in HTML.

Creating an HTML Template

Create a templates directory and add index.html inside:

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Welcome, {{ name }}!</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Rendering the Template

from flask import render_template

@app.route('/welcome/<string:name>')
def welcome(name):
    return render_template('index.html', name=name)
Enter fullscreen mode Exit fullscreen mode

Using Control Structures in Jinja2

<ul>
{% for item in items %}
    <li>{{ item }}</li>
{% endfor %}
</ul>
Enter fullscreen mode Exit fullscreen mode

Extending Templates

Create base.html:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    <nav>My Navigation Bar</nav>
    {% block content %}{% endblock %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Extend in another template:

{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
    <h1>Welcome to my site!</h1>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

5. Handling Forms and User Authentication

To handle user input, Flask provides the request object.

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        return f"Welcome, {username}"
    return '''<form method="post">Username: <input type="text" name="username"><input type="submit"></form>'''
Enter fullscreen mode Exit fullscreen mode

User Authentication with Flask-Login

from flask_login import LoginManager, UserMixin, login_user, logout_user

login_manager = LoginManager()
login_manager.init_app(app)

class User(UserMixin):
    pass
Enter fullscreen mode Exit fullscreen mode

6. Flask with Databases (SQLAlchemy)

Flask supports integration with databases using SQLAlchemy.

from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))

    def __repr__(self):
        return f"<User {self.name}>"
Enter fullscreen mode Exit fullscreen mode

Fetching Data from Database

@app.route('/users')
def get_users():
    users = User.query.all()
    return {"users": [user.name for user in users]}
Enter fullscreen mode Exit fullscreen mode

7. Advanced Backend Concepts in Flask

Middleware Implementation

@app.before_request
def before_request():
    print("Before handling request")
Enter fullscreen mode Exit fullscreen mode

Background Tasks with Celery

from celery import Celery

app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])

@celery.task
def background_task(x, y):
    return x + y
Enter fullscreen mode Exit fullscreen mode

Caching with Flask-Cache

from flask_caching import Cache

app.config['CACHE_TYPE'] = 'simple'
cache = Cache(app)

@cache.cached(timeout=60)
@app.route('/cached')
def cached_view():
    return "This is a cached response."
Enter fullscreen mode Exit fullscreen mode

WebSockets with Flask-SocketIO

from flask_socketio import SocketIO

socketio = SocketIO(app)

@socketio.on('message')
def handle_message(msg):
    print('Received message:', msg)
Enter fullscreen mode Exit fullscreen mode

Read that article with Examples

Conclusion

Flask is a powerful framework that provides the flexibility to develop everything from simple web pages to complex APIs. By mastering Flask, developers can efficiently build scalable and maintainable applications. This guide covered everything from setup to deployment, authentication, databases, middleware, caching, WebSockets, and background tasks, providing a strong foundation for working with Flask.

Retry later

Top comments (0)

Retry later