⚠️ Status: untested. This extension is provided as-is and has not been tested in production. Please feel free to fork, modify, improve, and open pull requests.Licensed under GNU GPLv3 (see LICENSE).
A pure-ASGI middleware that checks each request against the ip-block.com service. Works with any Starlette-based app, including FastAPI.
Targets: Starlette 0.20+ / FastAPI 0.80+, Python 3.8+ (async, uses httpx).
pip install ip-block-asgiFastAPI:
fromfastapiimportFastAPIfromip_block_asgiimportIpBlockMiddlewareapp=FastAPI()
app.add_middleware(
IpBlockMiddleware,
site_id="your-site-id",
api_key="your-api-key",
behind_proxy=True,
whitelist=["127.0.0.1", "10.0.0.0/8"],
)Starlette:
fromstarlette.applicationsimportStarlettefromstarlette.middlewareimportMiddlewarefromip_block_asgiimportIpBlockMiddlewareapp=Starlette(middleware=[
Middleware(IpBlockMiddleware, site_id="your-site-id", api_key="your-api-key"),
])enabled=Truesite_id=""api_key=""api_url="https://api.ip-block.com/v1/check"fail_open=True# allow on error/timeoutcache_ttl=300# seconds (in-memory cache)timeout=1.0# secondsbehind_proxy=False# trust X-Forwarded-For / CF-Connecting-IPblock_action="403"# "403" or "redirect"redirect_url="https://www.ip-block.com/blocked.php"block_message="Access denied."whitelist=[] # IPs and CIDR ranges- Builds
{api_key, site_id, ip, user_agent, referrer}andPOSTs it via an asynchttpx.AsyncClientwith a 1 second timeout. - Blocks only when the response is
{"action":"block"}. - Fails open on any error/timeout/non-2xx/missing
action(fail_open=Falseto fail closed). - Caches each decision for
cache_ttlseconds in-process, keyed bymd5(ip|user_agent|referrer). - Honours
whitelist(individual IPs and CIDR ranges). - Reads the real client IP from the ASGI scope; with
behind_proxy=Trueit trustsCF-Connecting-IPthen the firstX-Forwarded-Forhop.