sanic-limiter
sanic-limiter copied to clipboard
How to catch the rate limit exception?
I am using your limiter, which is great!
However, I can’t seem to redirect user to a custom page using the exception catching mechanism in sanic. For example:
import sanic_limiter
from sanic import Blueprint
bp_error = Blueprint('Errors and Exception Handling')
@bp_error.exception(sanic_limiter.errors.RateLimitExceeded)
def handle_over_rate_limit(request, exception):
logger.exception(request.headers.get('x-forwarded-for'), exception)
return request.app.jinja.render(
"errors/rate_limit.html",
request,
status=429
)
If I raise the exception directly on an endpoint, I can see that this custom page is shown. However, if a user hits the limit, it just outputs the exception in plain text. What can I do to achieve what I wanted?
can you post more code? have this blueprint registered?
Sorry for the late reply. Yes, this blueprint is registered.
will this suffice? I don’t know how much code you need to see because most of it has nothing to do with the ratelimiter
# app.py
from sanic import Sanic
from sanic_jinja2 import SanicJinja2
from sanic_limiter import Limiter
from cr import blueprints
def get_remote_address(request):
ip_title = request.headers.get('X-Forwarded-For')
return ip_title or '127.0.0.1'
app = Sanic(__name__)
app.jinja = SanicJinja2(
app,
line_statement_prefix='%',
extensions=[
'jinja2_time.TimeExtension',
'jinja2.ext.do',
'jinja2.ext.i18n'
])
bps = [
blueprints.bp_admin,
blueprints.bp_blog,
blueprints.bp_error,
# truncated
]
for bp in bps:
app.blueprint(bp)
limiter = Limiter(app, global_limits=['1/second', '20/minute', '1000/hour', '5000/day'], key_func=get_remote_address)