Stop form spam in Flask

Updated

This guide adds Bot403 to a contact form in Flask. The browser solves a small proof of work. Then a view checks the token with one call to the bot403 package, before it accepts the message. The visitor sees no puzzle, and the script sets no cookie. The free plan covers 5,000 checks a month and needs no card.

The example uses Flask 3.1.3, Flask-WTF 1.3.0 for the CSRF check, and bot403 0.1.0 from PyPI. The bot403 package needs Python 3.10 or newer and uses only the standard library.

Before you start

Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). Put the secret key in an environment variable, never in your code or your repository. Flask-WTF also needs a Flask secret key to sign its CSRF tokens.

Terminal
uv add flask flask-wtf bot403        # or: pip install flask flask-wtf bot403
export BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY
export FLASK_SECRET_KEY=a-long-random-string

The app below is a package called contact, with this layout:

Layout
contact/
  __init__.py          # create_app()
  views.py             # the blueprint with the form
  templates/contact.html
tests/
  test_contact.py

1. The app factory

create_app() turns on CSRF protection and makes one Bot403 client for the app. The client reads BOT403_SECRET_KEY. It gets a 5-second timeout here. The default is 10 seconds.

contact/__init__.py
from bot403 import Bot403
from flask import Flask
from flask_wtf import CSRFProtect

csrf = CSRFProtect()


def create_app(config=None, bot403=None):
    app = Flask(__name__)
    app.config.from_prefixed_env()  # FLASK_SECRET_KEY becomes SECRET_KEY
    app.config.update(config or {})
    csrf.init_app(app)

    # Create the client here, not at import time.
    # Bot403() reads BOT403_SECRET_KEY and raises ValueError without it.
    app.extensions["bot403"] = bot403 or Bot403(timeout=5)

    from . import views

    app.register_blueprint(views.bp)
    return app

2. The template

The script tag protects every form on the page. Before the browser sends the form, the script adds a hidden _bot403 field with the token. The csrf_token field is for Flask-WTF.

contact/templates/contact.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Contact</title>
  <script src="https://bot403.com/v1/bot403.js" data-bot403-key="pk_live_YOUR_PUBLIC_KEY" async></script>
</head>
<body>
  <form method="post" action="{{ url_for('contact.contact') }}">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <label>Email <input name="email" type="email" required></label>
    <label>Message <textarea name="message" required></textarea></label>
    <button type="submit">Send</button>
  </form>
</body>
</html>

3. The view

The view sends the form fields to Bot403. verify_form() posts them to https://bot403.com/api/v1/verify with your secret key. The view accepts the message only when the answer is ok. If Bot403 does not answer, the view accepts the form and logs a warning. A wrong secret key or too many verify calls a minute raise an error, so you see them and fix them.

contact/views.py
from bot403 import Bot403Error
from flask import Blueprint, abort, current_app, redirect, render_template, request, url_for

bp = Blueprint("contact", __name__)


def bot403_check(form):
    # 1. Post the whole form. Bot403 reads the _bot403 field and the honeypot field.
    #    The CSRF token stays on your server.
    fields = {k: v for k, v in form.items() if k != "csrf_token"}
    try:
        result = current_app.extensions["bot403"].verify_form(fields)
    except Bot403Error as e:
        if e.status != 0:
            raise  # 401 wrong key, 429 too many calls: fix these, do not hide them
        current_app.logger.warning("bot403 did not answer, letting the form through: %s", e)
        return True
    # 2. Refuse when ok is false, except for reason "quota"
    return result.ok or result.reason == "quota"


@bp.route("/contact", methods=["GET", "POST"])
def contact():
    if request.method == "POST":
        if not bot403_check(request.form):
            abort(400)
        # A real visitor: send the email or store the message here
        return redirect(url_for("contact.thanks"))
    return render_template("contact.html")


@bp.get("/thanks")
def thanks():
    return "Thanks. Your message is on its way."

A failed token is a normal answer, not an exception: result.ok is False and result.reason says why. The verify page lists every reason.

The trap: Flask-WTF and the csrf_token field

With CSRFProtect on, Flask-WTF refuses a POST without a valid csrf_token field. It answers with "Bad Request: CSRF token missing" (HTTP 400), before your view runs. Keep the check. CSRF stops other sites that send forms in the name of your visitor. Bot403 does not do that job. It stops scripts that send forms automatically. Do not add @csrf.exempt to the view to make a spam test pass.

This has three results:

  • The view removes csrf_token before it posts the form. As a result, the CSRF token stays on your server.
  • A test with curl gets 400 from Flask-WTF, not from Bot403. Test the view with the Flask test client and WTF_CSRF_ENABLED = False, as in "Test it".
  • If FLASK_SECRET_KEY is not set, csrf_token() fails when the page renders. Flask-WTF needs a secret key to sign the token.

Why the client is made in create_app

Make the Bot403 client inside create_app(), not at the top of a module. Bot403() raises ValueError when BOT403_SECRET_KEY is not set. At import time, that error stops every flask command and every test, even ones that never send a form. Inside the factory, a test can pass its own client, and the app reads the real key only when it starts.

Forms sent with fetch

If you send the form with fetch, send it as FormData. Then the CSRF token and the honeypot field go with it. The script listens to the submit event before your own code does. It waits for the token, puts it in the _bot403 field, and then submits again. So when your handler runs, the form already holds the token:

contact.js
const form = document.querySelector("form");
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  // holds csrf_token, _bot403 and the honeypot field
  const res = await fetch(form.action, { method: "POST", body: new FormData(form) });
  if (res.ok) location.href = res.url;
});

If your front end sends JSON, put the CSRF token in the X-CSRFToken header and the token in the body. On the server, call bot403.verify(token) instead of verify_form(). This sends the token alone, so Bot403 cannot check the honeypot field. Use FormData when you can.

Test it

The tests give the app a fake client with a fixed answer. As a result, the tests need no network and no key:

tests/test_contact.py
from bot403 import Bot403Error, Result

from contact import create_app


class FakeBot403:
    """Stands in for the Bot403 client: no network, no key."""

    def __init__(self, answer):
        self.answer, self.sent = answer, None

    def verify_form(self, form):
        self.sent = dict(form)
        if isinstance(self.answer, Exception):
            raise self.answer
        return self.answer


def client(answer):
    fake = FakeBot403(answer)
    app = create_app({"TESTING": True, "WTF_CSRF_ENABLED": False}, bot403=fake)
    return app.test_client(), fake


def test_verified_form_goes_through():
    c, fake = client(Result(ok=True))
    r = c.post("/contact", data={"email": "[email protected]", "_bot403": "token"})
    assert r.status_code == 302 and r.headers["Location"] == "/thanks"
    assert fake.sent["_bot403"] == "token"


def test_failed_token_is_refused():
    c, _ = client(Result(ok=False, reason="invalid"))
    assert c.post("/contact", data={"email": "[email protected]"}).status_code == 400


def test_bot403_down_lets_the_form_through():
    c, _ = client(Bot403Error("network", 0, "network"))
    assert c.post("/contact", data={"email": "[email protected]"}).status_code == 302
Terminal
python -m pytest -q tests

Then run flask --app contact run. Open /contact. Send the form. The browser goes to /thanks, and the site in your dashboard shows one check. If you get a failure that you do not expect, read the troubleshooting page. It lists every reason and its fix. For Django, read Stop form spam in Django. For FastAPI, read Stop form spam in FastAPI.

Stop spam, not customers.

The CAPTCHA your visitors never see.

Get started free