# Django

URL: https://iscredible.com/docs/integrations/django

> Protect Django signup views and expensive actions with the Python SDK.

Call isCredible from the Django view that creates accounts, before you save the user or send any email.

## Install

```bash
pip install is-credible
```

Add `ISCREDIBLE_API_KEY` to your server's environment. The package needs Python 3.9 or later and has no dependencies.

## A small helper

Create the client once at import time and reuse it. It is thread-safe.

accounts/risk.py:

```python
import logging
import os

from iscredible import IsCredible, IsCredibleError, decide

log = logging.getLogger(__name__)
client = IsCredible(api_key=os.environ["ISCREDIBLE_API_KEY"], timeout=3, max_retries=1)

def client_ip(request):
    # Behind a proxy or load balancer, use the address it forwards. Otherwise REMOTE_ADDR.
    forwarded = request.META.get("HTTP_X_FORWARDED_FOR")
    return forwarded.split(",")[0].strip() if forwarded else request.META.get("REMOTE_ADDR")

def screen(data, scenario_id=None):
    """Returns APPROVE, REVIEW or DENY. Returns APPROVE when the check can't run (fail open)."""
    try:
        action, _reasons = decide(client.verify(data, scenario_id=scenario_id))
        return action
    except IsCredibleError as error:
        if error.status == 402:
            log.error("isCredible: no active plan, checks are paused (%s)", error.code)
        elif error.status == 429:
            log.warning("isCredible: rate limit or daily quota reached")
        else:
            log.warning("isCredible unavailable, allowing the request: %s", error)
    except ValueError as error:  # invalid input, e.g. a malformed email
        log.warning("isCredible input rejected: %s", error)
    return "APPROVE"
```

Only trust `X-Forwarded-For` when your app runs behind a proxy you control, because clients can set it themselves.

## Protect the signup view

accounts/views.py:

```python
from django.contrib.auth import get_user_model
from django.http import JsonResponse
from django.views.decorators.http import require_POST

from .risk import client_ip, screen

@require_POST
def signup(request):
    email = request.POST["email"]

    action = screen({
        "email": email,
        "ip": client_ip(request),
        "userAgent": request.META.get("HTTP_USER_AGENT"),
        "deviceId": request.POST.get("deviceId") or None,
        "accountCreation": True,
    })

    if action == "DENY":
        return JsonResponse({"error": "We couldn't create your account."}, status=403)

    user = get_user_model().objects.create_user(
        username=email, email=email, password=request.POST["password"],
        is_active=(action == "APPROVE"),  # REVIEW: activate after email verification
    )
    return JsonResponse({"id": user.pk})
```

`None` values are fine: fields you don't have are left out of the checks. Never send the password to isCredible.

## Protect expensive actions

Check usage before costly work. `check_usage` caches each answer and only calls the API when a check is due.

```python
from iscredible import IsCredibleError
from .risk import client, client_ip

def generate(request):
    try:
        decision = client.check_usage(
            str(request.user.pk),
            {"metric": "ai_tokens", "used": tokens_used_this_month(request.user), "limit": 100000},
            {"ip": client_ip(request)},
        )
        if decision["action"] == "DENY":
            return JsonResponse({"error": "Free limit reached"}, status=429)
    except IsCredibleError:
        pass  # fail open
    ...
```

## Acting on the decision

| Decision | Suggested action |
|---|---|
| APPROVE | Create an active account |
| REVIEW | Create it inactive, or hold back free credits, until the email or phone is verified |
| DENY | Return a neutral error. Don't say which check fired |

## Errors and limits

| Situation | What to do |
|---|---|
| Timeout, network error or 5xx | The SDK retries, then raises `IsCredibleError`. Fail open and log it |
| `429` rate limit or daily quota | The SDK retries with backoff, then raises. Fail open, and upgrade if it happens every day |
| `402` with `code` `trial_ended` or `subscription_ended` | Your account has no active plan. Fail open and choose a plan in the dashboard |
| `401` or `403` | The key is wrong, revoked or missing. Fix it; fail open meanwhile |

See the [Python SDK](https://iscredible.com/docs/sdks/python) for every option.
