Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 6, 2022 04:12 pm GMT

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

Step #2 - Usage

from flask import Flaskfrom flask_debugtoolbar import DebugToolbarExtensionapp = Flask(__name__)# the toolbar is only enabled in debug mode:app.debug = True# Inject the toolbar toolbar = DebugToolbarExtension(app)

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

Step #2 - Usage in Code

from flask import Flaskfrom flask_marshmallow import Marshmallow  # <-- NEWapp = Flask(__name__)ma = Marshmallow(app)                      # <-- NEW  

Define a model

from Flask-SqlAchemy import Model, Column, Integer, String, DateTimeclass User(Model):    email = Column(String)    password = Column(String) 

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)

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)

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

Step #2 - Usage

from flask import Flaskfrom flask.ext.cache import Cacheapp = Flask(__name__)# Check Configuring Flask-Cache section for more detailscache = Cache(app,config={'CACHE_TYPE': 'simple'})

Cache views (via a decorator)

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

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

Step #2 - Usage in code

from flask import Flaskfrom flask_minify import Minifyapp = Flask(__name__)Minify(app=app, html=True, js=True, cssless=True)

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

from flask import Flaskfrom flask_minify import Minify, decorators as minify_decoratorsapp = 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>'

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

Step #2 - Usage in code

from flask import Flaskfrom flask_limiter import Limiterfrom flask_limiter.util import get_remote_addressapp = 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.exemptdef ping():    return "PONG"

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


Original Link: https://dev.to/sm0ke/flask-useful-extensions-debugtoolbar-cache-rate-limiter-2c76

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To