Skip to content

Commit

Permalink
Raise a werkzeug exception when the user is over their rate limit
Browse files Browse the repository at this point in the history
Returning a body and status code means that this response will be
sent directly to the client as text/plain.
Using an exception allows us to use flask's request error handling to
format the error using the upstream app's configuration so that we can,
for example, format the error as JSON for API responses and HTML for
website responses.
  • Loading branch information
alastair committed Aug 11, 2021
1 parent 1832109 commit c02af8c
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions brainzutils/ratelimit.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
#
import time
from functools import update_wrapper

from flask import request, g
from werkzeug.exceptions import TooManyRequests

from brainzutils import cache

# g key for the timeout when limits must be refreshed from cache
Expand Down Expand Up @@ -155,8 +158,9 @@ def on_over_limit(limit):
'''
Set a nice and readable error message for over the limit requests.
'''
return 'You have exceeded your rate limit. See the X-RateLimit-* response headers for more ' \
'information on your current rate limit.\n', 429
raise TooManyRequests(
'You have exceeded your rate limit. See the X-RateLimit-* response headers for more ' \
'information on your current rate limit.')


def check_limit_freshness():
Expand Down

0 comments on commit c02af8c

Please sign in to comment.