DEV Community

Cover image for Flask Useful Extensions - DebugToolbar, Cache, Rate Limiter
Sm0ke
Sm0ke

Posted on • Originally published at blog.appseed.us

Flask Useful Extensions - DebugToolbar, Cache, Rate Limiter

Hello coders!

This article presents a short-list with Flask Libraries and Extensions we can use to make our projects faster or stable. For newcomers, Flask is a leading framework powered by Python that we can use to code simple sites, APIs, or complex eCommerce solutions.


Thanks for reading! Content provided by App Generator

  • 👉 Flask-DebugToolbar - useful in the development phase
  • 👉 Flask-Marshmallow - for API development
  • 👉 Flask-Cache - for blazing-fast websites
  • 👉 Flask-Minify - HTML & assets compression
  • 👉 Flask-Limiter - rate limiter for Flask

✨ Flask-DebugToolbar

This extension adds a toolbar overlay to Flask applications containing useful information for debugging. Once this module is installed we should be able to see in the browser things like HTTP headers, configuration, or even profiling information.

👉 Step #1 - Installation

$ pip install flask-debugtoolbar
Enter fullscreen mode Exit fullscreen mode

👉 Step #2 - Usage

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)

# the toolbar is only enabled in debug mode:
app.debug = True

# Inject the toolbar 
toolbar = DebugToolbarExtension(app)
Enter fullscreen mode Exit fullscreen mode

The toolbar will automatically be injected into HTML responses when debug mode is on. In production, setting app.debug = False will disable the toolbar.


Flask Debug Toolbar.


✨ Flask Marshmallow

Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that optionally integrates with Flask-SQLAlchemy.

👉 Step #1 - Installation

$ pip install flask-marshmallow
Enter fullscreen mode Exit fullscreen mode

👉 Step #2 - Usage in Code

from flask import Flask
from flask_marshmallow import Marshmallow  # <-- NEW

app = Flask(__name__)
ma = Marshmallow(app)                      # <-- NEW  
Enter fullscreen mode Exit fullscreen mode

Define a model

from Flask-SqlAchemy import Model, Column, Integer, String, DateTime

class User(Model):
    email = Column(String)
    password = Column(String) 
Enter fullscreen mode Exit fullscreen mode

Define your output format with marshmallow.

class UserSchema(ma.Schema):
    class Meta:
        # Fields to expose
        fields = ("email")

user_schema  = UserSchema()
users_schema = UserSchema(many=True)
Enter fullscreen mode Exit fullscreen mode

Define API nodes

@app.route("/api/users/")
def users():
    all_users = User.all()
    return users_schema.dump(all_users)


@app.route("/api/users/<id>")
def user_detail(id):
    user = User.get(id)
    return user_schema.dump(user)
Enter fullscreen mode Exit fullscreen mode

✨ Flask Cache

This extension might help us to reduce the performance issues that sometimes occur in our projects and also speed up the response for static pages.

👉 Step #1 - Installation

$ pip install Flask-Cache
Enter fullscreen mode Exit fullscreen mode

👉 Step #2 - Usage

from flask import Flask
from flask.ext.cache import Cache

app = Flask(__name__)
# Check Configuring Flask-Cache section for more details
cache = Cache(app,config={'CACHE_TYPE': 'simple'})
Enter fullscreen mode Exit fullscreen mode

Cache views (via a decorator)

@cache.cached(timeout=50)
def index():
    return render_template('index.html')
Enter fullscreen mode Exit fullscreen mode

✨ Flask Minify

This extension provides a runtime compression of served pages and optionally to assets (JSS, CSS). This optimization might improve the SEO score of our projects and also the overall experience for our users.

👉 Step #1 - Installation

$ pip install Flask-Minify
Enter fullscreen mode Exit fullscreen mode

👉 Step #2 - Usage in code

from flask import Flask
from flask_minify import Minify

app = Flask(__name__)
Minify(app=app, html=True, js=True, cssless=True)
Enter fullscreen mode Exit fullscreen mode

The extension effect can be isolated to a single view using the passive flag and decorators:

from flask import Flask
from flask_minify import Minify, decorators as minify_decorators

app = Flask(__name__)
Minify(app=app, passive=True)   # <-- Passive mode enabled

@app.route('/')
@minify_decorators.minify(html=True, js=True, cssless=True)
def example():
  return '<h1>Example...</h1>'
Enter fullscreen mode Exit fullscreen mode

✨ Flask Limiter

Flask-Limiter provides rate limiting features to Flask applications. Flask-Limiter can be configured to persist the rate limit state to many commonly used storage backends via the limits library.

👉 Step #1 - Installation

$ pip install Flask-Limiter
Enter fullscreen mode Exit fullscreen mode

👉 Step #2 - Usage in code

from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["200 per day", "50 per hour"]
)
@app.route("/slow")
@limiter.limit("1 per day")
def slow():
    return ":("

@app.route("/medium")
@limiter.limit("1/second", override_defaults=False)
def medium():
    return ":|"

@app.route("/fast")
def fast():
    return ":)"

@app.route("/ping")
@limiter.exempt
def ping():
    return "PONG"
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! For more resources and support, feel free to access:


Top comments (2)

Collapse
 
uithemes profile image
ui-themes • Edited

I'm using DebugToolbar and Minify in all my projects.
Thanks for sharing

Collapse
 
sm0ke profile image
Sm0ke

🚀🚀