Skip to main content

Fast CaptchaX

Captcha Validator for FastAPI

Install

pip install fast_captchax

Usage

sync version

from datetime import timedelta
from fastapi import FastAPI
from fast_captchax import captcha
from fast_captchax.memory import MemoryCapatchStore
from fast_captchax.redis import RedisCapatchStore
from captchax import create_image

validate, captcha_router = captcha(
    generator = CaptchaXGenerator(),
    store = MemoryCapatchStore(), # memory captcha store is only used for test. please use RedisCapatchStore in production
    expire_in = timedelta(minutes=2), # by default is 2 minutes
    captcha_cookie_name = None, # by default _captcha_session_id
    captcha_field_name = None, # verify api form field, by default _captcha
)

app = FastAPI()
app.include_router(captcha_router, prefix="/api")

in your form

<form>
  <img
    alt="Captcha"
    name="_captcha"
    src="/api/captcha/"
    onclick="this.src = '/api/captcha/?t=' + Date.now();"
  />
</form>

You can check your captcha in JS for better user experience.

let formData = new FormData();
formData.append("_captcha", "user input captcha");
resp = await fetch("/api/verify", { body: formData });
resp.status == 200; // if captcha is correct
resp.status == 429; // if captcha is incorrect, Please refresh captcha.

check in your server

from fastapi import Response, status
@app.get("/your_api")
def api(user_input=Annotated[str | None, Form(alias="_captcha")],
    session: Annotated[str | None, Cookie(alias="_captcha")] = None):
    if validate(session, user_input):
        return Response(status_code=status.HTTP_429_TOO_MANY_REQUESTS)

if you have called verify API previously.

from fastapi import Response, status
@app.get("/your_api")
def api(session: Annotated[str | None, Cookie(alias="_captcha")] = None):
    if validate(session):
        return Response(status_code=status.HTTP_429_TOO_MANY_REQUESTS)

We also provide async version.

Please use

from datetime import timedelta
from fastapi import FastAPI
from fast_captchax import async_captcha
from captchax import create_image
from fast_captchax.memory import AsyncMemoryCapatchStore
from fast_captchax.redis import AsyncRedisCapatchStore

async def async_create_image():
    return await asyncio.to_thread(CaptchaXGenerator())

validate, captcha_router = async_captcha(
    generator = async_create_image,
    store = AsyncMemoryCapatchStore(), # memory captcha store is only used for test. please use RedisCapatchStore in production
    expire_in = timedelta(minutes=2), # by default is 2 minutes
    captcha_cookie_name = None, # by default _captcha_session_id
    captcha_field_name = None, # verify api form field, by default _captcha
)

app = FastAPI()
app.include_router(captcha_router, prefix="/api")

check in your server.

from fastapi import Response, status
@app.get("/your_api")
async def api(user_input=Annotated[str | None, Form(alias="_captcha")],
    session: Annotated[str | None, Cookie(alias="_captcha")] = None):
    if await validate(session, user_input):
        return Response(status_code=status.HTTP_429_TOO_MANY_REQUESTS)

if you have called verify API previously.

from fastapi import Response, status
@app.get("/your_api")
async def api(session: Annotated[str | None, Cookie(alias="_captcha")] = None):
    if await validate(session):
        return Response(status_code=status.HTTP_429_TOO_MANY_REQUESTS)

Example

poetry run uvicorn example:app

Metadata

Release files for fast-captchax 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fast-captchax 0.1.0
File Size Uploaded
fast_captchax-0.1.0.tar.gz 4.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fast-captchax 0.1.0
File Interpreter ABI Platform
fast_captchax-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 10.0 kB

Release files / fast_captchax-0.1.0.tar.gz

Download URL fast_captchax-0.1.0.tar.gz
Size 4.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a83b4b9d6f7b281ee691baac77a57c202252a721a938fd463c0574e707eda3f0
BLAKE2b-256 checksum
How to use checksums
f80d1d79f1d1ae910a09687bff4cbd61be101e7069947ae7f228f74debc529ad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.2 CPython/3.12.2 Darwin/23.4.0

Release files / fast_captchax-0.1.0-py3-none-any.whl

Download URL fast_captchax-0.1.0-py3-none-any.whl
Size 5.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
60f2837c5018e870bedb3d76d55fd663668081a22b77eac829174390fecf2a73
BLAKE2b-256 checksum
How to use checksums
30800b95d57fc8e94af9c9c9e6bcafc6cf09c737e65f55521c2b5c92ac250d22
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.2 CPython/3.12.2 Darwin/23.4.0

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page