Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block an IP address from accessing my Flask app on Heroku?

I've got an IP address that I need to block from my website. Running a Flask app on Heroku, and I'm seeing 50 requests per second on my server, and that definitely shouldn't be happening.

I'm familiar with using htaccess on an Apache server, is there anything similar here (Gunicorn server)?

like image 814
user3740806 Avatar asked Jun 14 '14 16:06

user3740806


2 Answers

Use the flask before_request decorator. This will get called before each request so you can check a list of banned ip addresses. Any banned address will be aborted with 403, forbidden.

from flask import request, abort, current_app as app

ip_ban_list = ['127.0.0.1']

@app.before_request
def block_method()
    ip = request.environ.get('REMOTE_ADDR')
    if ip in ip_ban_list:
        abort(403)
like image 52
Martlark Avatar answered Nov 16 '22 03:11

Martlark


Try using the pre_request server hook from Gunicorn:

def pre_request(worker, req):
    if req.remote_addr != 'ip to be blocked':
        pass
like image 2
paulo.filip3 Avatar answered Nov 16 '22 03:11

paulo.filip3