Install the Botmotive guard in Django
This page helps you add botmotive-django to a Django project, so it applies the fixes you choose in Botmotive.
The middleware enforces your rules: blocks, throttles, allow rules and path denials. It also serves Botmotive's robots.txt section and, when the RSL license is on, /license.xml. It also sends a compact record of each request to Botmotive, so you don't need another log source. If you already send logs from Railway, Cloudflare, Fastly or your own server, set BOTMOTIVE_LOGS=off so requests aren't counted twice.
What you need first
- A Botmotive account and a site. See Getting started.
- Your site ID, such as
my-shop. It is shown in Settings next to Site ID. - A token for the guard, which starts with
bm_. It needs both Fetch blocking rules and Send traffic logs. - Django 4.2 or later, and Python 3.9 or later.
A new site starts with no token. Its install page makes one for you: open your site, choose Django (or click Connection steps in Settings), and click Make a token. The token is shown only once, and Botmotive keeps only a hash of it. You can also make one in Settings:
- Open your site in the dashboard and click Settings.
- Under Tokens, click New token. Name it after what will use it, such as
Django app, and click Make token. - Click Copy and store the token somewhere safe.
Other tokens keep working. If an old token may have leaked, click Revoke next to it.
Install
Install the package:
pip install botmotive-django==0.2.0Add the app, and the middleware near the top of
MIDDLEWARE, insettings.py. The app addsmanage.py botmotive_checkand a startup warning when the site or token is missing.INSTALLED_APPS = [ # ...your apps "botmotive_django", ] MIDDLEWARE = [ "botmotive_django.middleware.BotmotiveMiddleware", # ...your other middleware ]Give it your site ID and token. Either set environment variables:
BOTMOTIVE_SITE=my-shop BOTMOTIVE_TOKEN=bm_...Or add a
BOTMOTIVEdict tosettings.py. A key in the dict wins over the matching environment variable.import os BOTMOTIVE = { "site": "my-shop", "token": os.environ["BOTMOTIVE_TOKEN"], }Without a site and token, the middleware does nothing.
Serve robots.txt from Django. Add this to your root
urls.py, before any catch-all pattern:from django.urls import include, path urlpatterns = [ path("", include("botmotive_django.urls")), # serves /robots.txt # ...your other URLs ]If your web server or a static files app serves its own
robots.txt, remove it. Otherwise Django never sees the request.Restart your app.
Settings that matter
| Dict key | Environment variable | Default |
|---|---|---|
site, token |
BOTMOTIVE_SITE, BOTMOTIVE_TOKEN |
none |
api |
BOTMOTIVE_API |
https://api.botmotive.io |
ip_header |
BOTMOTIVE_IP_HEADER |
none, so REMOTE_ADDR is used |
cache |
BOTMOTIVE_CACHE |
default |
refresh |
none | 60 seconds |
robots |
none | "User-agent: *\nAllow: /" |
serve_license |
none | True |
logs |
BOTMOTIVE_LOGS (off, 0, false or no) |
on |
Logs. Each worker queues a short record of each request (method, path, status, user agent, IP, timing and header names) and a background thread sends them gzipped every 10 seconds or 500 requests. It never sends cookies, the Authorization header or request bodies, and secret-looking query values, such as token or password, become redacted. At most 10,000 records wait in memory, and the oldest go first. Turn logs off with "logs": False or BOTMOTIVE_LOGS=off when another source already sends this site's logs.
Client IP. By default the middleware uses REMOTE_ADDR. Behind a load balancer, that is the balancer's address. Set ip_header to a header that only your edge sets: x-real-ip, x-forwarded-for, cf-connecting-ip, fly-client-ip or true-client-ip. With x-forwarded-for, the middleware takes the rightmost public address. The header is trusted as-is, so never pick one visitors can set. The one exception is cf-connecting-ip, which counts only when REMOTE_ADDR is a Cloudflare range or a private address. If the header holds no valid address, it falls back to REMOTE_ADDR.
Cache across several workers. The rules feed and throttle counters live in Django's cache. The local-memory cache is per process. With several workers or servers, use a shared backend such as Redis, Memcached or the database cache. Set cache to that cache's alias if it isn't default.
BOTMOTIVE = {"site": "my-shop", "token": os.environ["BOTMOTIVE_TOKEN"], "cache": "shared"}
robots.txt. The view serves your robots lines first, then Botmotive's section between # BEGIN Botmotive and # END Botmotive. When the RSL license is on, the section starts with a License: line.
/license.xml. When Serve an RSL license at /license.xml is ticked in Settings, the middleware answers /license.xml. Set serve_license to False to stop that.
Paths. Path rules read the raw request URI when the server passes it on. gunicorn and uWSGI do. This stops //xmlrpc.php and /xmlrpc%2Ephp slipping past a rule for /xmlrpc.php.
Domain. In Settings, fill in Domain under Your site's address, then click Save. Botmotive then reads your robots.txt and sitemap once a day.
Check it worked
Run the check where your app runs, with the same settings:
python manage.py botmotive_checkIt prints
PASSorFAILfor the token, the API, your rules and a test log record, and exits with an error if any step fails. Within a minute, your site's page in the dashboard shows Guard connected: Django, last seen just now.Open
https://example.com/robots.txt. You should see your own lines. If you have chosen AI bot rules in Settings, you also see the# BEGIN Botmotivesection.Check traffic is arriving. Open your site in the dashboard and click the 15m tab.
Once requests arrive, the dashboard says Receiving data with a count of requests so far. Results follow 15 to 30 minutes after the first request, and the dashboard opens on the tab that has them.
Apply a block fix to a bot in the dashboard. Within a minute or so, request your site with that bot's user agent:
curl -i -A 'ExampleBot/1.0' https://example.com/You should see
403andForbidden.. A throttled visitor gets429with aRetry-Afterheader.
Updating and removing
- To update, run
pip install --upgrade botmotive-djangoand restart your app. - To use a new token, change
BOTMOTIVE_TOKEN(or thetokenkey) and restart. - To remove it, delete the middleware line, the
include("botmotive_django.urls")line and anyBOTMOTIVEsettings. Then runpip uninstall botmotive-django. Put back a staticrobots.txtif you need one.
If something goes wrong
The middleware fails open. If Botmotive can't be reached, the last rules stay in force. Every error lets the request through. Problems are logged to the botmotive logger.
- "fetching the rules feed failed". Check the site ID, the token and that your server can reach
api.botmotive.io. - Throttles don't trip, or trip unevenly. Each worker has its own local-memory cache. Use a shared cache.
- IP rules don't match. Set
ip_header. See Client IP above.
For more, see Troubleshooting.