Flask-Limiterを使用して削除に制限を掛ける

This commit is contained in:
yuuki
2025-01-24 12:09:41 +09:00
parent 2fc9165081
commit a5aca4fada
2 changed files with 27 additions and 6 deletions

32
app.py
View File

@@ -19,8 +19,7 @@ import traceback
import pprint import pprint
import pathlib import pathlib
import shutil import shutil
from random import randint from flask_limiter import Limiter
import datetime
import flask import flask
import nkf import nkf
@@ -46,6 +45,30 @@ def take_config(name, required=False):
return None return None
app = Flask(__name__) app = Flask(__name__)
def get_remote_address() -> str:
return flask.request.headers.get("CF-Connecting-IP") or flask.request.headers.get("X-Forwarded-For") or flask.request.remote_addr or "127.0.0.1"
limiter = Limiter(
get_remote_address,
app=app,
# default_limits=[],
# storage_uri="memory://",
# Redis
storage_uri=os.environ.get("REDIS_URI", "redis://127.0.0.1:6379/"),
# Redis cluster
# storage_uri="redis+cluster://localhost:7000,localhost:7001,localhost:70002",
# Memcached
# storage_uri="memcached://localhost:11211",
# Memcached Cluster
# storage_uri="memcached://localhost:11211,localhost:11212,localhost:11213",
# MongoDB
# storage_uri="mongodb://localhost:27017",
# Etcd
# storage_uri="etcd://localhost:2379",
strategy="fixed-window", # or "moving-window"
)
client = MongoClient(host=os.environ.get("TAIKO_WEB_MONGO_HOST") or take_config('MONGO', required=True)['host']) client = MongoClient(host=os.environ.get("TAIKO_WEB_MONGO_HOST") or take_config('MONGO', required=True)['host'])
basedir = take_config('BASEDIR') or '/' basedir = take_config('BASEDIR') or '/'
@@ -827,11 +850,8 @@ def upload_file():
return flask.jsonify({'success': True}) return flask.jsonify({'success': True})
@app.route("/api/delete", methods=["POST"]) @app.route("/api/delete", methods=["POST"])
@limiter.limit("1 per day")
def delete(): def delete():
rand = randint(1, 100)
if rand != 100:
return f"{rand} は 100 ではありません。", 403
id = flask.request.get_json().get('id') id = flask.request.get_json().get('id')
client["taiko"]["songs"].delete_one({ "id": id }) client["taiko"]["songs"].delete_one({ "id": id })

View File

@@ -11,5 +11,6 @@ redis==5.2.1
requests==2.32.3 requests==2.32.3
websockets==14.2 websockets==14.2
nkf==1.0.4 nkf==1.0.4
Flask-Limiter==3.10.1
git+https://github.com/yuukiwww/tjaf.git@d59e854b074012f6a31bd4c65b53edb6148b0ac7 git+https://github.com/yuukiwww/tjaf.git@d59e854b074012f6a31bd4c65b53edb6148b0ac7
git+https://github.com/jcrist/msgspec.git@29390b0385cda4ba76a0aaf4ede5d54ae9ff35ff git+https://github.com/jcrist/msgspec.git@29390b0385cda4ba76a0aaf4ede5d54ae9ff35ff