0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoで簡単にレート制限するなら django-ratelimit

Posted at

Django で API やフォームを作っていると、

・スパム投稿を防ぎたい

・API の叩きすぎを防止したい

・BOT 対策を入れたい

という場面がよくあります。

そんなときに 最小コストで導入できるのが django-ratelimit です。

django-ratelimit とは

django-ratelimit は ビュー単位で簡単にレート制限をかけられる Django 用ライブラリです。

IP / ユーザー単位で制限可能

デコレーター1行で導入できる

429 を自動で返せる

Django 標準のキャッシュを利用

インストール

pip install django-ratelimit

一番シンプルな使い方

from django.http import JsonResponse
from ratelimit.decorators import ratelimit

@ratelimit(key='ip', rate='5/m', block=True)
def sample_view(request):
    return JsonResponse({"message": "OK"})

設定内容

・key='ip' IPアドレスごとに制限
・rate='5/m' 1分に5回まで
・block=True 超えたら自動で 429 を返す

👉 これだけでレート制限完了

制限されたかを自分で制御したい場合

@ratelimit(key='ip', rate='10/m', block=False)
def my_view(request):
    if getattr(request, "limited", False):
        return JsonResponse(
            {"error": "Too many requests"},
            status=429
        )
    return JsonResponse({"ok": True})

block=False にすると自動ブロックしない

request.limited で判定できる

レート指定の書き方

5/s # 1秒に5回
10/m # 1分に10回
100/h # 1時間に100回

複数制限も可能

@ratelimit(key='ip', rate='5/s')
@ratelimit(key='ip', rate='100/h')
def view(request):
    ...

CBV(Class Based View)で使う場合

from django.views import View
from ratelimit.decorators import ratelimit
from django.utils.decorators import method_decorator

@method_decorator(
    ratelimit(key='ip', rate='10/m', block=True),
    name='dispatch'
)
class MyView(View):
    def get(self, request):
        ...

どんな場面で使える?

ログイン・問い合わせフォーム

API エンドポイント

検索機能

コメント・投稿機能

👉 スパム対策の第一歩としてかなり優秀

まとめ

django-ratelimit は 導入がとにかく簡単

デコレーター1行で実用レベル

Django 標準キャッシュと相性が良い

小〜中規模サービスには十分

「とりあえずレート制限入れたい」なら最適解です。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?