Reduce persistent profile creation (#1772)

* Reduce persistent profile creation

* mypy

* actually we want /compile to update last_request_date
This commit is contained in:
Mark Street
2025-12-15 16:18:49 +00:00
committed by GitHub
parent a78f7d9ef0
commit bb19ab0dff
2 changed files with 33 additions and 3 deletions

View File

@@ -1,4 +1,5 @@
import logging
import re
from typing import Callable, TYPE_CHECKING, Union
from django.contrib import auth
@@ -40,6 +41,27 @@ def disable_csrf(
return middleware
def is_public_request(req: Request) -> bool:
methods_paths = [
("GET", "/api/compiler"),
("GET", "/api/library"),
("GET", "/api/platform"),
("GET", "/api/preset"),
("GET", "/api/scratch-count$"),
("GET", "/api/scratch/[A-Za-z0-9]+/compile$"),
("GET", "/api/scratch/[A-Za-z0-9]+$"),
("GET", "/api/scratch$"),
("GET", "/api/search$"),
("GET", "/api/stats$"),
("GET", "/api/users"),
]
for method, path in methods_paths:
if req.method == method and re.match(path, req.path):
return True
return False
def set_user_profile(
get_response: Callable[[HttpRequest], Response],
) -> Callable[[Request], Response]:
@@ -57,13 +79,19 @@ def set_user_profile(
"curl",
"YandexRenderResourcesBot",
"SentryUptimeBot",
"Discord",
]
# Avoid creating profiles for SSR or bots
# Avoid creating persistent profiles for SSR or bots
if not user_agent or any(bot in user_agent for bot in bot_signatures):
request.profile = Profile()
return get_response(request)
# Avoid creating persistent for public endpoints
if is_public_request(request):
request.profile = Profile()
return get_response(request)
profile = None
# Try user-linked profile

View File

@@ -13,7 +13,7 @@ class RequestTests(APITestCase):
Ensure that we create a profile for a normal request
"""
response = self.client.get(reverse("compilers"), HTTP_USER_AGENT="browser")
response = self.client.get(reverse("current-user"), HTTP_USER_AGENT="browser")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Profile.objects.count(), 1)
@@ -23,7 +23,9 @@ class RequestTests(APITestCase):
Ensure that we don't create profiles for node-fetch requests (SSR)
"""
response = self.client.get(reverse("compilers"), HTTP_USER_AGENT="node-fetch")
response = self.client.get(
reverse("current-user"), HTTP_USER_AGENT="node-fetch"
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Profile.objects.count(), 0)