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

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fast_captchax-0.1.0.tar.gz (4.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fast_captchax-0.1.0-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file fast_captchax-0.1.0.tar.gz.

File metadata

  • Download URL: fast_captchax-0.1.0.tar.gz
  • Upload date:
  • Size: 4.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.12.2 Darwin/23.4.0

File hashes

Hashes for fast_captchax-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a83b4b9d6f7b281ee691baac77a57c202252a721a938fd463c0574e707eda3f0
MD5 96923f5d49997d4ab643798defcdf4e0
BLAKE2b-256 f80d1d79f1d1ae910a09687bff4cbd61be101e7069947ae7f228f74debc529ad

See more details on using hashes here.

File details

Details for the file fast_captchax-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: fast_captchax-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 5.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.12.2 Darwin/23.4.0

File hashes

Hashes for fast_captchax-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 60f2837c5018e870bedb3d76d55fd663668081a22b77eac829174390fecf2a73
MD5 72241024d005fc7c1a5962afe9490cd0
BLAKE2b-256 30800b95d57fc8e94af9c9c9e6bcafc6cf09c737e65f55521c2b5c92ac250d22

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page