Python Tutorial 56 – Utilise Flask Limiter to Customise Rate Limits By the Characteristic of Incoming Requests

The fundamental approach of SaaS or BaaS or API monetization is to provide customers with different service and plan options by customizing the rate limits. So users can select and buy the plan quota they think it’s sufficient and pay for a reasonable price. Flask limiter has existing modules and parameters for your application to adopt. It’s easy and lightweight to upgrade your SaaS with this extension.

flask limiter

The fundamental approach of SaaS or BaaS or API monetization is to provide customers with different services and plans. So users can select and buy the plan quota they think it’s sufficient and pay for a reasonable price. Flask limiter has existing modules and parameters for your application to adopt and build these functions. It’s easy and lightweight to upgrade your SaaS with this extension.

In this Python tutorial, I’ll talk about Flask Limiter and relevant features and parameters. By the end of this article, you can master the skills and start equipping your application with the Flask rate limits, which are used to set and provide different plans for buyers.

What’s Flask Limiter

Flask limiter is a Flask extension package that can let us easily add rate-limiting functionality to an endpoint. Apart from limiting the rate, it can also put the rate limit information in the HTTP header by using the RATELIMIT_HEADERS_ENABLED configuration. Therefore, we don’t need to code the HTTP header information ourselves. Besides that, it also supports a configurable backend for storage with current implementations for Redis, in-memory, Memcached, and others.

It provides rate limiting features to Flask applications. By adding the extension to your flask application, you can configure various rate limits at different levels and tiers. They are things such as application-wide, per Blueprint, routes, resources, etc. 

A default rate limit of 200 per day and 50 per hour is applied to all routes. We can even set multiple limits, we just need to delimit them using a delimiter. For example, we can set the limit to 100 requests per minute and 1000 requests per hour, at the same time.

Installation and Module Import

To install the Flask limiter, we can open the computer terminal and input pip3 install Flask-limiter. It just takes 10 seconds to complete the installation.

Then, we need to import the flask limiter modules and libraries into your Python script. Below are the two main modules.

from flask_limiter import Limiter

from flask_limiter.util import get_remote_address

The limiter is the constructor and we can create a global level of limiter that configure with the Flask App. Meanwhile, get_remote_addresss is the key_func value to identify the IP address of the user who requests the data.

Initialize the Limiter Globally

flask limiter

app = Flask(__name__)

limiter = Limiter(app, key_func=get_remote_address, default_limits=["10 per day"])

By using the constructor – limiter, we can configure the limiter with the Flask App. In this configuration, it can be set the default rating limits, key_func which is the get_remote_address.

Decorates to Declare Rate Limit

Apart from the global default limit set in the configuration, we can custom the rating limits by using the decorator – limit in each Flask application route. 

For example, there are some core parameters that are often used to decorate the route. They are the limit value, exempt_when, key_func/lambda, and error_message. Below is the sample of using these parameters to create a decorator in a route.

flask limiter

@limiter.limit(

"100/month", 

key_func = lambda : current_user.username,

error_message=’Sorry buddy, your request has exceeded 100 times a month’,

Exempt_when = lambda: current_user.is_admin

)

key_func/lambda is to extract the unique identifier for the rate limit. The default value is the remote address of the request. But we can custom and set up for specific current users by using flask login. For the details about user authentications, I would release other articles to elaborate.

Share_Limit()

For scenarios where a rate limit should be shared by multiple routes. For example when you want to protect routes using the same resource with an umbrella rate limit.

Usually, the approach is to create a variable that has the instance limiter and the method shared_limit

kol_limit = limiter.shared_limit("100/month", scope="kol")

In the shared_limit method, we can set the limit value and the scope. Then, the variable can be used in the routes you want them to share with each other.

@app.route("..")

@kol_limit

def kol1():

    ...

@app.route("..")

@kol_limit

def kol2():

    ...

exempt_when

Each limit can be exempted when given conditions are fulfilled. These conditions can be specified by supplying a callable as a exempt_when argument when defining the limit.

Exempt_when is very helpful as it can exclude some situations that don’t match the user identity. For example, if I’m a prestige member visiting a page, the page request limit can be different from other members. So the limit value in this route is for other members. On the other hand, the prestige member might use the global one or another one from a custom function.

Full Sample of Python and Flask Limiter Script

If you are interested in the full python Tutorial 56 – Utilise Flask Limiter to Customise Rate Limits By the Characteristic of Incoming Requests, please subscribe to our newsletter by adding the message “Python Tutorial 56”. We would send you the script immediately to your mailbox.

I hope you enjoy reading Python Tutorial 56 – Utilise Flask Limiter to Customise Rate Limits By the Characteristic of Incoming Requests. If you did, please support us by doing one of the things listed below, because it always helps out our channel.

  • Support my channel through PayPal (paypal.me/Easy2digital)
  • Subscribe to my channel and turn on the notification bell Easy2Digital Youtube channel.
  • Follow and like my page Easy2Digital Facebook page
  • Share the article to your social network with the hashtag #easy2digital
  • Buy products with Easy2Digital 10% OFF Discount code (Easy2DigitalNewBuyers2021)
  • You sign up for our weekly newsletter to receive Easy2Digital latest articles, videos, and discount code on Buyfromlo products and digital software
  • Subscribe to our monthly membership through Patreon to enjoy exclusive benefits (www.patreon.com/louisludigital)