{"id":34070096,"url":"https://github.com/kirisaki77/response-bandwidth-limiter","last_synced_at":"2026-04-02T17:29:36.650Z","repository":{"id":283336260,"uuid":"950650189","full_name":"kirisaki77/response-bandwidth-limiter","owner":"kirisaki77","description":"A response bandwidth limiting middleware for FastAPI and Starlette. It allows you to limit the response sending speed for specific endpoints.","archived":false,"fork":false,"pushed_at":"2025-03-27T12:24:22.000Z","size":65,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-18T21:26:04.181Z","etag":null,"topics":["bandwidth","fastapi","limiter","response","starlette"],"latest_commit_sha":null,"homepage":"https://github.com/kirisaki77/response-bandwidth-limiter","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kirisaki77.png","metadata":{"files":{"readme":"README.ja.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-03-18T13:39:00.000Z","updated_at":"2025-10-16T08:35:38.000Z","dependencies_parsed_at":"2025-12-14T07:03:05.783Z","dependency_job_id":null,"html_url":"https://github.com/kirisaki77/response-bandwidth-limiter","commit_stats":null,"previous_names":["kirisaki77/response-bandwidth-limiter"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/kirisaki77/response-bandwidth-limiter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kirisaki77%2Fresponse-bandwidth-limiter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kirisaki77%2Fresponse-bandwidth-limiter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kirisaki77%2Fresponse-bandwidth-limiter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kirisaki77%2Fresponse-bandwidth-limiter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kirisaki77","download_url":"https://codeload.github.com/kirisaki77/response-bandwidth-limiter/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kirisaki77%2Fresponse-bandwidth-limiter/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31311617,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-02T12:59:32.332Z","status":"ssl_error","status_checked_at":"2026-04-02T12:54:48.875Z","response_time":89,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bandwidth","fastapi","limiter","response","starlette"],"created_at":"2025-12-14T07:01:55.048Z","updated_at":"2026-04-02T17:29:36.641Z","avatar_url":"https://github.com/kirisaki77.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Response Bandwidth Limiter\n\n*他の言語で読む: [English](README.md), [日本語](README.ja.md)*\n\nFastAPIとStarlette用のレスポンス帯域制限ミドルウェア。特定のエンドポイントのレスポンス送信速度を制限することができます。\n\n## インストール\n\npipを使用してインストールできます：\n\n```bash\npip install response-bandwidth-limiter\n```\n\n### 依存関係\n\nこのライブラリは最小限の依存関係で動作しますが、実際の使用にはFastAPIまたはStarletteが必要です。\n必要に応じて以下のようにインストールしてください：\n\n```bash\n# FastAPIと一緒に使用する場合\npip install fastapi\n\n# Starletteと一緒に使用する場合\npip install starlette\n\n# 開発やテストに必要な依存関係を含める場合\npip install response-bandwidth-limiter[dev]\n```\n\n## 基本的な使い方\n\n### デコレータを使った方法（推奨）\n\n```python\nfrom fastapi import FastAPI, Request\nfrom starlette.responses import FileResponse\nfrom response_bandwidth_limiter import ResponseBandwidthLimiter, ResponseBandwidthLimitExceeded, _response_bandwidth_limit_exceeded_handler\n\n# リミッターの初期化\nlimiter = ResponseBandwidthLimiter()\napp = FastAPI()\n\n# アプリケーションに登録\napp.state.response_bandwidth_limiter = limiter\napp.add_exception_handler(ResponseBandwidthLimitExceeded, _response_bandwidth_limit_exceeded_handler)\n\n# エンドポイントのレスポンス帯域制限（1024 bytes/sec）\n@app.get(\"/download\")\n@limiter.limit(1024)  # 1024 bytes/sec\nasync def download_file(request: Request):\n    return FileResponse(\"path/to/large_file.txt\")\n\n# 別のエンドポイントに別の制限（2048 bytes/sec）\n@app.get(\"/video\")\n@limiter.limit(2048)  # 2048 bytes/sec\nasync def stream_video(request: Request):\n    return FileResponse(\"path/to/video.mp4\")\n```\n\n### Starletteでの使用例\n\n```python\nfrom starlette.applications import Starlette\nfrom starlette.responses import FileResponse\nfrom starlette.routing import Route\nfrom response_bandwidth_limiter import ResponseBandwidthLimiter\n\n# デコレータ方式\nlimiter = ResponseBandwidthLimiter()\n\nasync def download_file(request):\n    return FileResponse(\"path/to/large_file.txt\")\n\n# デコレータを適用\ndownload_with_limit = limiter.limit(1024)(download_file)\n\n# ルートを定義\nroutes = [\n    Route(\"/download\", endpoint=download_with_limit)\n]\n\napp = Starlette(routes=routes)\n\n# リミッターをアプリに登録\nlimiter.init_app(app)\n```\n\n## 高度な使用例\n\n### デコレータを使った帯域制限の設定（シンプルなケース）\n\nシンプルに帯域制限を設定する場合は、`set_response_bandwidth_limit`デコレータを使用できます：\n\n```python\nfrom fastapi import FastAPI\nfrom starlette.responses import FileResponse\nfrom response_bandwidth_limiter import set_response_bandwidth_limit\n\napp = FastAPI()\n\n@app.get(\"/download\")\n@set_response_bandwidth_limit(1024)  # 1024 bytes/sec\nasync def download_file():\n    return FileResponse(\"path/to/large_file.txt\")\n```\n\nこの方法では、`ResponseBandwidthLimiter`クラスを初期化せずに、直接エンドポイントに帯域制限を設定できます。\nさらに、このデコレータを使用する場合は、ミドルウェアを明示的に追加する必要があります：\n\n```python\nfrom response_bandwidth_limiter import ResponseBandwidthLimiterMiddleware\n\napp = FastAPI()\napp.add_middleware(ResponseBandwidthLimiterMiddleware)\n\n@app.get(\"/download\")\n@set_response_bandwidth_limit(1024)\nasync def download_file():\n    return FileResponse(\"path/to/large_file.txt\")\n```\n\nこのシンプルなデコレータはグローバルな設定を使用するため、複数のアプリケーションで同じ関数名を使用する場合は注意してください。より複雑なシナリオでは、`ResponseBandwidthLimiter`クラスを使用するアプローチが推奨されます。\n\n### シンプルデコレータと標準デコレータの違い\n\nシンプルデコレータ (`set_response_bandwidth_limit`) と標準デコレータ (`ResponseBandwidthLimiter.limit`) の主な違い：\n\n1. シンプルデコレータ:\n   - グローバルな設定を使用\n   - アプリインスタンスに依存しない\n   - 複数アプリで同名の関数を使うと競合する可能性あり\n   - 設定が簡単\n\n2. 標準デコレータ:\n   - アプリインスタンスごとに分離された設定\n   - 複数のアプリで安全に使用可能\n   - より明示的な初期化が必要\n   - 大規模アプリに適している\n\n### 両方のデコレータを併用する\n\n同じアプリ内で両方のデコレータを使用することもできます：\n\n```python\nfrom fastapi import FastAPI, Request\nfrom response_bandwidth_limiter import (\n    ResponseBandwidthLimiter,\n    set_response_bandwidth_limit,\n    ResponseBandwidthLimiterMiddleware\n)\n\napp = FastAPI()\nlimiter = ResponseBandwidthLimiter()\napp.state.response_bandwidth_limiter = limiter\n\n# ミドルウェアは一度だけ追加\napp.add_middleware(ResponseBandwidthLimiterMiddleware)\n\n# 標準デコレータの使用例\n@app.get(\"/video\")\n@limiter.limit(2048)\nasync def stream_video(request: Request):\n    # ...\n\n# シンプルデコレータの使用例\n@app.get(\"/download\")\n@set_response_bandwidth_limit(1024)\nasync def download_file(request: Request):\n    # ...\n```\n\n### 動的な帯域制限\n\n実行時に帯域制限を変更したい場合：\n\n```python\nlimiter = ResponseBandwidthLimiter()\napp = FastAPI()\napp.state.response_bandwidth_limiter = limiter\n\n@app.get(\"/admin/set-limit\")\nasync def set_limit(endpoint: str, limit: int):\n    limiter.routes[endpoint] = limit\n    return {\"status\": \"success\", \"endpoint\": endpoint, \"limit\": limit}\n```\n\n**重要な注意点**: 帯域制限の変更は永続的です。一度エンドポイントの帯域制限を変更すると、その変更はサーバーが再起動されるまで保持され、次回以降のすべてのリクエストに適用されます。一時的な変更ではなく、設定の更新として扱われます。\n\n例えば、あるエンドポイントの制限を1000 bytes/secから2000 bytes/secに変更した場合、それ以降のすべてのリクエストは2000 bytes/secの制限で処理されます。元の速度に戻す場合は、明示的に再設定する必要があります。\n\n### 特定のユーザーやIPに対する帯域制限\n\n```python\n@app.get(\"/download/{user_id}\")\n@limiter.limit(1024)\nasync def download_for_user(request: Request, user_id: str):\n    # ユーザーごとに異なる制限を適用したい場合は、\n    # ここでカスタム処理を行うことができます\n    user_limits = {\n        \"premium\": 5120,\n        \"basic\": 1024\n    }\n    user_type = get_user_type(user_id)\n    actual_limit = user_limits.get(user_type, 512)\n    # ...レスポンス処理\n```\n\n## 制限事項と注意点\n\n- 帯域制限はサーバーサイドで適用されるため、クライアント側の帯域幅やネットワーク状況によっては、実際の転送速度が変わる場合があります。\n- 大きなファイル転送の場合は、メモリ使用量に注意してください。\n- 分散システムの場合、各サーバーごとに制限が適用されます。\n\n## APIリファレンス\n\nこのセクションでは、ライブラリが提供する主なクラスとメソッドの詳細なリファレンスを提供します。\n\n### ResponseBandwidthLimiter\n\nレスポンス帯域制限の機能を提供するメインクラスです。\n\n```python\nclass ResponseBandwidthLimiter:\n    def __init__(self, key_func=None):\n        \"\"\"\n        レスポンス帯域幅制限機能を初期化します\n        \n        引数:\n            key_func: 将来的な拡張用のキー関数（現在は使用されていません）\n        \"\"\"\n        \n    def limit(self, rate: int):\n        \"\"\"\n        エンドポイントに対して帯域制限を適用するデコレータを返します\n        \n        引数:\n            rate: 制限する速度（bytes/sec）\n            \n        戻り値:\n            デコレータ関数\n            \n        例外:\n            TypeError: rateが整数でない場合\n        \"\"\"\n        \n    def init_app(self, app):\n        \"\"\"\n        FastAPIまたはStarletteアプリケーションにリミッターを登録します\n        \n        引数:\n            app: FastAPIまたはStarletteアプリケーションインスタンス\n        \"\"\"\n```\n\n### ResponseBandwidthLimiterMiddleware\n\nFastAPIおよびStarlette用のミドルウェアで、帯域制限を実際に適用します。\n\n```python\nclass ResponseBandwidthLimiterMiddleware(BaseHTTPMiddleware):\n    def __init__(self, app):\n        \"\"\"\n        帯域制限ミドルウェアを初期化します\n        \n        引数:\n            app: FastAPIまたはStarletteアプリケーション\n        \"\"\"\n        \n    def get_handler_name(self, request, path):\n        \"\"\"\n        パスに一致するハンドラー名を取得します\n        \n        引数:\n            request: リクエストオブジェクト\n            path: リクエストパス\n            \n        戻り値:\n            str または None: エンドポイント名（存在する場合）\n        \"\"\"\n        \n    async def dispatch(self, request, call_next):\n        \"\"\"\n        リクエストに対して帯域制限を適用します\n        \n        引数:\n            request: リクエストオブジェクト\n            call_next: 次のミドルウェア関数\n            \n        戻り値:\n            レスポンスオブジェクト\n        \"\"\"\n```\n\n### set_response_bandwidth_limit\n\nシンプルな帯域制限デコレータです。\n\n```python\ndef set_response_bandwidth_limit(limit: int):\n    \"\"\"\n    エンドポイントごとに帯域制限を設定するシンプルなデコレータ\n    \n    引数:\n        limit: 制限する速度（bytes/sec）\n        \n    戻り値:\n        デコレータ関数\n    \"\"\"\n```\n\n### ResponseBandwidthLimitExceeded\n\n帯域制限超過時に発生する例外です。\n\n```python\nclass ResponseBandwidthLimitExceeded(Exception):\n    \"\"\"\n    帯域幅の制限を超過した場合に発生する例外\n    \n    引数:\n        limit: 制限値（bytes/sec）\n        endpoint: 制限が適用されたエンドポイント名\n    \"\"\"\n```\n\n### エラーハンドラ\n\n```python\nasync def _response_bandwidth_limit_exceeded_handler(request, exc):\n    \"\"\"\n    帯域幅制限超過時のエラーハンドラー\n    \n    引数:\n        request: リクエストオブジェクト\n        exc: ResponseBandwidthLimitExceeded例外\n        \n    戻り値:\n        JSONResponse: HTTPステータスコード429と説明\n    \"\"\"\n```\n\n### ユーティリティ関数\n\n```python\ndef get_endpoint_name(request):\n    \"\"\"\n    リクエストからエンドポイント名を取得します\n    \n    引数:\n        request: リクエストオブジェクト\n    \n    戻り値:\n        str: エンドポイント名\n    \"\"\"\n    \ndef get_route_path(request):\n    \"\"\"\n    リクエストからルートパスを取得します\n    \n    引数:\n        request: リクエストオブジェクト\n        \n    戻り値:\n        str: ルートパス\n    \"\"\"\n```\n\n## ソースコード\n\nこのライブラリのソースコードは以下のGitHubリポジトリで公開されています：\nhttps://github.com/kirisaki77/response-bandwidth-limiter\n\n## 謝辞\n\nこのライブラリは [slowapi](https://github.com/laurentS/slowapi) (MIT Licensed) にインスパイアされました。\n\n## ライセンス\n\nMPL-2.0\n\n## PyPI\n\nhttps://pypi.org/project/response-bandwidth-limiter/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkirisaki77%2Fresponse-bandwidth-limiter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkirisaki77%2Fresponse-bandwidth-limiter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkirisaki77%2Fresponse-bandwidth-limiter/lists"}