10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

flaskでIP制限をかける

Posted at

動機

APIサーバーからのアクセスのみ反応するようにしたい
直接叩かれた時は403を返したい

(もっと下のレイヤーで制限をかけるのが正解なのかもしれないけれど、メモ代わりに残しておきます)

ソース

下記は例です

from flask import Flask, request

app = Flask(__name__, static_folder=None)

#許可するIP一覧
ACCEPTED_IP = ["127.0.0.1", "192.168.11.2"]

def ip_check(func):
    def wrapper(*args, **kwargs):
        if request.remote_addr in ACCEPTED_IP:
            print('IP Check : OK')
            return func(*args, **kwargs)
        else:
            print("403")
            return abort(403)
    return wrapper


@app.route('/', methods=['GET'])
@ip_check
def index():
    return "hi"

# main
if __name__ == "__main__":
    print(app.url_map)
    app.run(host='localhost', port=5001)
10
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?