use case · python

Python spam detection, one HTTP call away.

Updated November 7, 2026

SiftFy works from Python without a framework adapter: POST the text to /v1/predict with requests or httpx and read a calibrated 0–1 probability back. Use the official siftfy package for typed responses, set a two-second timeout, fail open, and only drop above the response's max_confidence. Queue the 0.50-to-ceiling band for review.

The same pattern works in Django, FastAPI, Flask, Celery, and a plain script. The hard part is not the HTTP call; it is choosing thresholds that do not throw away real leads.

the dependency-free path

Twenty lines with requests.

A sync client is enough for most Django and Flask views. The important parts are the timeout, the fail-open branch, and returning the ceiling alongside the probability so the caller can make a three-way decision.

pythonA sync scorer that fails open
# pip install requests
import os
import requests

def score(text: str) -> tuple[float, float | None]:
    try:
        response = requests.post(
            "https://api.siftfy.io/v1/predict",
            headers={"X-API-Key": os.environ["SIFTFY_KEY"]},
            json={"text": text},
            timeout=2.0,
        )
        response.raise_for_status()
        data = response.json()
        return data["spam_probability"], data.get("max_confidence")
    except requests.RequestException:
        # Fail open: a classifier outage must not lose a real lead.
        return 0.0, None

If you would rather use the official client, it adds typed responses and retries for transient failures:

pythonpip install siftfy
# pip install siftfy
import os
from siftfy import Siftfy

client = Siftfy(api_key=os.environ["SIFTFY_KEY"], timeout=2.0)
result = client.predict("Win a free iPhone! Click here NOW")

print(result.spam_probability)  # 0.65
print(result.max_confidence)    # 0.84
print(result.likelihood)        # "medium"

response shape

What the API returns.

FieldTypeUse it for
spam_probabilitynumberCalibrated score from 0 to 1. At or above 0.50 it enters the review band.
likelihoodlow | medium | highCoarse display bucket. Not a routing field; route on the probability and ceiling.
max_confidencenumberThe highest score the model may return on its own word. Read it from each response.
detected_languagestringLanguage code used for calibration. Non-English ceilings can be lower.
model_versionstringTraceable model and calibration revision for logs.
score_sourcemodel | typesafeWho produced the score. Most integrations only branch on the probability.
Allow0.00–0.50
Review0.50–ceiling
Drop> ceiling
The ceiling is max_confidence from each response, not a constant. The bar shows 0.84 as an example; read the real value per request.

django

Classify in the view, not the model.

Keep the network call out of Model.save(). Classify after form validation, store the score and a review flag, and return the same success response whether the submission was allowed or silently dropped.

pythonDjango view with a silent drop and a review flag
# app/services/spam.py
from .client import score

def classify_message(message: str) -> tuple[float, str]:
    probability, ceiling = score(message)
    if ceiling is not None and probability > ceiling:
        return probability, "drop"
    if probability >= 0.50:
        return probability, "review"
    return probability, "allow"

# app/views.py
def contact(request):
    form = ContactForm(request.POST or None)
    if form.is_valid():
        probability, action = classify_message(form.cleaned_data["message"])
        if action == "drop":
            # Silent success: do not teach the spammer which field failed.
            return redirect("contact_thanks")
        submission = form.save(commit=False)
        submission.spam_probability = probability
        submission.needs_review = action == "review"
        submission.save()
        return redirect("contact_thanks")
    return render(request, "contact.html", {"form": form})

fastapi

Async without blocking the event loop.

Use httpx.AsyncClient, create it once at startup, and await the call inside the handler. A sync requests call inside an async route blocks the event loop for the duration of the timeout.

pythonFastAPI handler with a reused async client
# pip install fastapi httpx
import os
import httpx
from fastapi import FastAPI

app = FastAPI()
client = httpx.AsyncClient(timeout=2.0)

@app.post("/contact")
async def contact(payload: ContactSubmission):
    data = {"spam_probability": 0.0, "max_confidence": None}
    try:
        response = await client.post(
            "https://api.siftfy.io/v1/predict",
            headers={"X-API-Key": os.environ["SIFTFY_KEY"]},
            json={"text": payload.message},
        )
        response.raise_for_status()
        data = response.json()
    except httpx.HTTPError:
        pass  # fail open

    probability = data["spam_probability"]
    ceiling = data.get("max_confidence")

    if ceiling is not None and probability > ceiling:
        return {"ok": True}
    if probability >= 0.50:
        await queue_for_review(payload.email, payload.message, probability)
    else:
        await deliver_to_inbox(payload.email, payload.message)
    return {"ok": True}

The runnable FastAPI example has the full handler, and the Django example covers the form path.

tests

Prove the fail-open branch.

Most spam integrations break in the same two places: a timeout that raises into the user's request, and a hard-coded threshold above the model ceiling that never fires. Test both.

pythonpytest: fail-open and review-band assertions
# tests/test_spam.py
import pytest
from app.services import spam

def test_fails_open(monkeypatch):
    def boom(*args, **kwargs):
        raise requests.Timeout()
    monkeypatch.setattr(spam.requests, "post", boom)

    probability, ceiling = spam.score("hello")
    assert probability == 0.0
    assert ceiling is None

def test_review_band(monkeypatch):
    class Response:
        def raise_for_status(self): pass
        def json(self): return {"spam_probability": 0.62, "max_confidence": 0.84}

    monkeypatch.setattr(spam.requests, "post", lambda *a, **k: Response())
    assert spam.score("borderline") == (0.62, 0.84)

avoid these

Four Python mistakes that cost leads.

  • No timeout. The default is often unlimited. A slow provider becomes a hung worker.
  • Fail closed. A classifier outage should not take the contact form down with it.
  • Hard-coded 0.85. The model cannot reach that band alone. Use max_confidence.
  • Logging the message body. Log the score, action, and a truncated preview instead.

Python integration questions

Is there an official Python SDK for Siftfy?

Yes. The `siftfy` package on PyPI is the official client, built on httpx and type-checked under mypy strict. It supports sync and async use, typed responses, and retries for 408, 429, 5xx, and network errors. The raw `requests` example on this page is the dependency-free path if you would rather not add a package.

How do I call SiftFy from Django?

Put the classification call in a small service function, not in a model save or a template. Call it in the view or form handler after validation, store the probability and a review flag on the submission, and fail open on transport errors. Do not log full message bodies; log the score, the action, and a truncated preview.

How do I call SiftFy from FastAPI without blocking the event loop?

Use an async client such as httpx.AsyncClient and await the request inside the route handler. Create the client at startup and reuse it across requests so you keep connections warm. Set a 2-second timeout and catch httpx.HTTPError so the form fails open.

What timeout should a Python spam check use?

Two seconds is a sensible default for a contact form. SiftFy reports most calls under 10ms p99 from the same region, so two seconds is generous enough for a cold connection and short enough that a real visitor is not left waiting. Always pair the timeout with a fail-open branch.

What threshold should I use in Python?

Use 0.50 as the review floor and `max_confidence` from the response as the drop ceiling. A hard-coded 0.85 sits above the model's ceiling and never fires on model-only evidence. Allow below 0.50, queue from 0.50 to the ceiling, and drop only above the ceiling after a shadow run.

Does SiftFy work with Flask, Django, FastAPI, and plain scripts?

Yes. It is a single HTTPS POST with a JSON body, so any Python HTTP client works. The official SDK and the `requests` example both work in Django views, FastAPI handlers, Flask routes, Celery tasks, and standalone scripts. Keep the API key in an environment variable or secret manager.

start free

Score your first Python submission in five minutes.

10,000 requests a month free, no card. One endpoint, a calibrated probability, and no puzzle for your users.