Install DataPocket on Django

Updated

Two views and two URL patterns. Sign in and these snippets fill in your site ID and domain. Until then, swap YOUR_SITE_ID and YOUR_DOMAIN with the values from your Install page.

  1. 1

    views.py (pip install requests):

    py
    import requests
    from django.http import HttpResponse, Http404
    from django.views.decorators.csrf import csrf_exempt
    from django.views.decorators.http import require_POST
    
    PD = "https://datapocket.vo1d.studio"
    
    def dp_script(request, file):
        r = requests.get(f"{PD}/js/{file}", timeout=5)
        resp = HttpResponse(r.content, content_type="application/javascript")
        resp["Cache-Control"] = "public, max-age=3600"
        return resp
    
    @csrf_exempt
    @require_POST
    def dp_event(request):
        ip = request.META.get("HTTP_X_FORWARDED_FOR", request.META.get("REMOTE_ADDR", "")).split(",")[0].strip()
        r = requests.post(f"{PD}/api/event", data=request.body, timeout=5, headers={
            "Content-Type": "text/plain", "User-Agent": request.META.get("HTTP_USER_AGENT", ""), "X-Forwarded-For": ip})
        return HttpResponse(r.content, status=r.status_code, content_type="application/json")
  2. 2

    urls.py:

    py
    from django.urls import path, re_path
    from . import views
    
    urlpatterns = [
        re_path(r"^dp/js/(?P<file>script(\.[a-z]+)?(@\d+\.\d+\.\d+)?\.js)$", views.dp_script),
        path("dp/api/event", views.dp_event),
        # …your routes
    ]
  3. 3

    Then load the script from your own domain. Ad blockers can't tell it apart from your own code, so visits from people whose ad blocker blocks analytics domains are still counted:

    html
    <script
      defer
      data-site-id="YOUR_SITE_ID"
      data-domain="YOUR_DOMAIN"
      src="/dp/js/script.js"
    ></script>

Revenue attribution

  1. 1

    Pass the visitor cookie to Stripe Checkout so each sale is attributed to the channel that brought the buyer:

    py
    session = stripe.checkout.Session.create(
        # …your line_items, mode, success_url…
        metadata={
            "datapocket_visitor_id": request.cookies.get("dp_vid", ""),
            "datapocket_session_id": request.cookies.get("dp_sid", ""),
        },
    )
  2. 2

    Using another payment provider? Send payments from your backend (create an API key in Settings):

    bash
    curl -X POST https://datapocket.vo1d.studio/api/v1/payments \
      -H "Authorization: Bearer dpk_…" \
      -H "Content-Type: application/json" \
      -d '{"amount": 29.99, "currency": "USD", "transaction_id": "order_123", "visitor_id": "<dp_vid cookie>"}'

Related guides

Install DataPocket on Django · DataPocket