Docs·Proxy guide
Proxy with Django
One view serves Spreelytics from /sp/. It uses Requests: pip install requests. This guide uses /sp/. Any path works if nothing else on your site uses it and it doesn't contain words like "analytics" or "tracking", which blockers look for.
Add the view
Add this to one of your apps' views.py:
import requests
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
SCRIPTS = "https://cdn.spreelytics.com/cdn/sdk/"
API = "https://sdk.spreelytics.com/1.0/"
FORWARD = ["Content-Type", "User-Agent", "Origin", "Referer", "Accept", "Accept-Language"]
@csrf_exempt
def spreelytics_proxy(request, path):
url = SCRIPTS + path[3:] if path.startswith("js/") else API + path
if request.META.get("QUERY_STRING"):
url += "?" + request.META["QUERY_STRING"]
headers = {name: request.headers[name] for name in FORWARD if name in request.headers}
# The visitor's IP address. Behind a load balancer or CDN, take it from X-Forwarded-For instead.
headers["X-Forwarded-For"] = request.META.get("REMOTE_ADDR", "")
upstream = requests.request(request.method, url, data=request.body or None, headers=headers, timeout=10)
response = HttpResponse(upstream.content, status=upstream.status_code, content_type=upstream.headers.get("Content-Type"))
if "Cache-Control" in upstream.headers:
response["Cache-Control"] = upstream.headers["Cache-Control"]
return response
Add the URL
In your urls.py:
from django.urls import path
from . import views
urlpatterns = [
# ...your other URLs
path("sp/<path:path>", views.spreelytics_proxy),
]
Point the script at your proxy
In your Spreelytics snippet, load the script through /sp/js/ and add api_host:
<script src="/sp/js/spreelytics-loader.js"></script>
<script>
Spreelytics.init({
client_key: "YOUR_CLIENT_KEY",
api_host: "https://www.example.com/sp",
});
</script>
Check it works
Open your site with the browser's Network tab open and filtered by /sp/. The script files and
requests like track/page should come from your own domain, with status 200. In Spreelytics,
Settings → Tracking script says "Last seen just now" and Realtime shows you in your own country.
- Wrong country, or
200and nothing arrives: the proxy isn't passing the visitor's IP address inX-Forwarded-For. See The visitor's IP address below. 401: theOriginandRefererheaders didn't arrive, or your domain isn't in Allowed domains.
The visitor's IP address
REMOTE_ADDR is the connection's address. Behind a load balancer or Cloudflare, take the first address in request.META["HTTP_X_FORWARDED_FOR"] instead, or every visitor arrives from the load balancer's address.
Related
- Proxy overview: the other ways to set it up.
- Filter traffic: which traffic Spreelytics drops.