diff --git a/Pipfile b/Pipfile index 8cef6dd..6646e73 100644 --- a/Pipfile +++ b/Pipfile @@ -7,7 +7,10 @@ gunicorn = "*" decorator = "*" brotlipy = "*" gevent = "*" +redis = "*" +hiredis = "*" Flask = "*" +Flask-Limiter = "*" [packages.raven] extras = [ "flask",] diff --git a/httpbin/core.py b/httpbin/core.py index 221dbe0..c18d12a 100644 --- a/httpbin/core.py +++ b/httpbin/core.py @@ -16,6 +16,8 @@ import uuid import argparse from flask import Flask, Response, request, render_template, redirect, jsonify as flask_jsonify, make_response, url_for +from flask_limiter import Limiter +from flask_limiter.util import get_ipaddr from six.moves import range as xrange from werkzeug.datastructures import WWWAuthenticate, MultiDict from werkzeug.http import http_date @@ -57,6 +59,20 @@ app.debug = bool(os.environ.get('DEBUG')) if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) +# Setup rate-limiting. +if 'REDIS_URL' in os.environ: + app.config['RATELIMIT_STORAGE_URL'] = os.environ['REDIS_URL'] + app.config['RATELIMIT_HEADERS_ENABLED'] = True + + limiter = Limiter( + app, + key_func=get_ipaddr, + global_limits=["100000 per day", "10000 per hour"] + ) + + + + # Set up Bugsnag exception tracking, if desired. To use Bugsnag, install the # Bugsnag Python client with the command "pip install bugsnag", and set the # environment variable BUGSNAG_API_KEY. You can also optionally set