Skip to main content

moonito-python

Official Python SDK for Moonito — a smart analytics and visitor filtering platform designed to protect your website from unwanted traffic, bots, and malicious activity while providing deep visitor insights.

moonito-python is a lightweight Python SDK for integrating your web application with the Moonito Visitor Analytics API.

It allows you to:

  • Analyze and monitor web traffic intelligently
  • Filter out bots, crawlers, and unwanted visitors
  • Get real-time visitor behavior insights
  • Protect APIs, landing pages, and web apps automatically

Compatible with Flask, Django, FastAPI, and other Python web frameworks.

evaluate_visitor never raises. If the check cannot run (the API is unreachable, or refuses because a plan expired) it returns None, the visitor is let through, and the reason goes to the moonito logger. Moonito never turns into an error page on your site.

📦 Installation

pip install moonito

🚀 Quick Start

Flask Example

from flask import Flask, request, Response
from moonito import VisitorTrafficFiltering, Config

app = Flask(__name__)

# Initialize Moonito
client = VisitorTrafficFiltering(Config(
    is_protected=True,
    api_public_key="YOUR_PUBLIC_KEY",
    api_secret_key="YOUR_SECRET_KEY",
    unwanted_visitor_to="https://example.com/blocked",  # URL or HTTP status code
    unwanted_visitor_action=1  # 1 = Redirect, 2 = Iframe, 3 = Load content
))

@app.before_request
def check_visitor():
    """Middleware to check visitors before processing requests"""
    result = client.evaluate_visitor(request)
    
    if result:
        content = result['content']
        
        if isinstance(content, int):
            return Response(status=content)
        
        return Response(content, mimetype='text/html')

@app.after_request
def store_moonito_cookies(response):
    return client.apply_token(response)

@app.route('/')
def home():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(port=8080)

Django Example

# middleware.py
from moonito import VisitorTrafficFiltering, Config
from django.http import HttpResponse

class MoonitoMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        
        # Initialize Moonito
        self.client = VisitorTrafficFiltering(Config(
            is_protected=True,
            api_public_key="YOUR_PUBLIC_KEY",
            api_secret_key="YOUR_SECRET_KEY",
            unwanted_visitor_to="https://example.com/blocked",
            unwanted_visitor_action=1
        ))

    def __call__(self, request):
        # Check visitor
        result = self.client.evaluate_visitor(request)
        
        if result:
            content = result['content']
            
            if isinstance(content, int):
                return self.client.apply_token(HttpResponse(status=content))
            
            return self.client.apply_token(HttpResponse(content))
        
        response = self.get_response(request)
        return self.client.apply_token(response)

Add to settings.py:

MIDDLEWARE = [
    'your_app.middleware.MoonitoMiddleware',
    # ... other middleware
]

FastAPI Example

from fastapi import FastAPI, Request, Response
from starlette.concurrency import run_in_threadpool
from moonito import VisitorTrafficFiltering, Config

app = FastAPI()

# Initialize Moonito
client = VisitorTrafficFiltering(Config(
    is_protected=True,
    api_public_key="YOUR_PUBLIC_KEY",
    api_secret_key="YOUR_SECRET_KEY",
    unwanted_visitor_to="https://example.com/blocked",
    unwanted_visitor_action=1
))

@app.middleware("http")
async def moonito_middleware(request: Request, call_next):
    """Middleware to check visitors"""
    # Read the body first, so the SDK can forward the browser sensor's beacon.
    if request.method == "POST":
        await request.body()

    # In a thread, so a slow decision never stalls your other requests.
    result, cookies = await run_in_threadpool(client.evaluate_with_cookies, request)
    
    if result:
        content = result['content']
        
        if isinstance(content, int):
            return client.apply_cookies(Response(status_code=content), cookies)
        
        return client.apply_cookies(Response(content=content, media_type="text/html"), cookies)
    
    response = await call_next(request)
    return client.apply_cookies(response, cookies)

@app.get("/")
def read_root():
    return {"message": "Hello World"}

⚙️ Configuration

Field Type Description
is_protected bool Enable (True) or disable (False) protection
api_public_key str Your Moonito API public key (required)
api_secret_key str Your Moonito API secret key (required)
unwanted_visitor_to str URL to redirect unwanted visitors or HTTP error code
unwanted_visitor_action int Action for unwanted visitors: 1 = Redirect, 2 = Iframe, 3 = Load content
inject_sensor bool Add the browser sensor to your HTML pages in apply_token / apply_cookies. Default True, so there is no separate script to paste. Pages with a Content-Security-Policy, compressed or streamed responses are left untouched.

Since 2.3.0 the browser sensor is added for you through the apply_token / apply_cookies call you already make. If you pasted the sensor tag into your template before, you can remove it; it is never added twice.

Since 2.4.0 the sensor is served from your own site: its script, timing requests and beacon go to your page's own URL with a parameter unique to your site, and the SDK forwards the beacon to Moonito from your server. Visitors' browsers never contact another host, so ad blockers do not stop it. With FastAPI, read the request body before the check (await request.body(), as in the example above) so beacons can be forwarded.

🔧 Manual Evaluation

For custom implementations or manual checking:

from moonito import VisitorTrafficFiltering, Config

client = VisitorTrafficFiltering(Config(
    is_protected=True,
    api_public_key="YOUR_PUBLIC_KEY",
    api_secret_key="YOUR_SECRET_KEY"
))

# Manually evaluate a visitor
result = client.evaluate_visitor_manually(
    ip="8.8.8.8",
    user_agent="Mozilla/5.0",
    event="/home",
    domain="example.com"
)

if result['need_to_block']:
    print("Blocked visitor detected.")

💡 Use Cases

  • Prevent fake signups and bot traffic
  • Protect landing pages from ad click fraud
  • Collect accurate visitor analytics
  • Detect suspicious activity in real time

📋 Requirements

  • Python 3.7 or higher
  • No external dependencies (uses Python standard library)
  • Moonito API keys from https://moonito.net

🧪 Development

# Clone the repository
git clone https://github.com/moonito-net/moonito-python.git
cd moonito-python

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -e .
pip install pytest

# Run tests
pytest tests/

📄 License

MIT License © 2025 Moonito

🏷️ Keywords

python analytics sdk, moonito sdk, visitor filtering python, python bot protection, python traffic analytics, moonito python sdk, moonito api, website protection sdk python, moonito visitor analytics, python security sdk

🌐 Learn More

Visit https://moonito.net to learn more about:

  • Visitor analytics
  • Website traffic protection
  • API-based bot and fraud filtering

Moonito — Stop Bad Bots. Start Accurate Web Analytics.

Metadata

Release files for moonito 2.4.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 moonito 2.4.0
File Size Uploaded Provenance Actions
moonito-2.4.0.tar.gz 30.8 kB Without provenance Details for moonito-2.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for moonito 2.4.0
File Interpreter ABI Platform Actions
moonito-2.4.0-py3-none-any.whl Python 3 none any Details for moonito-2.4.0-py3-none-any.whl

Total release size: 52.8 kB

Release files / moonito-2.4.0.tar.gz

Download URL moonito-2.4.0.tar.gz
Size 30.8 kB
Tags Source
SHA-256 checksum
How to use checksums
819c4b7aa2fb7a930b88c088ae91b8eb7485217166d90303f384af7e33bfe20c
BLAKE2b-256 checksum
How to use checksums
a9a1001ac255b82df8618e1474c1d9adbd4a97001ed3eabb351893331a8b4446
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

Release files / moonito-2.4.0-py3-none-any.whl

Download URL moonito-2.4.0-py3-none-any.whl
Size 22.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f92e6a8b6cc45de1effaf45ede4636d4aecfe5a5b2a7fd41ba29178770806d21
BLAKE2b-256 checksum
How to use checksums
84ce14416bdcf5111ec02b27473a9b00445d667aaf0dd87a3d7a0f58d0ab4315
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

Security for moonito 2.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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