Skip to content

Commit 4ea41f5

Browse files
committed
CLEAN_NEEDED_BY caching
1 parent 2e089de commit 4ea41f5

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/reactpy_django/clean.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import logging
24
from datetime import datetime, timedelta
35
from typing import TYPE_CHECKING
@@ -10,8 +12,10 @@
1012
if TYPE_CHECKING:
1113
from reactpy_django.models import Config
1214

15+
CLEAN_NEEDED_BY: datetime = datetime(year=1, month=1, day=1)
16+
1317

14-
def clean_all(immediate: bool = False, ignore_config=False):
18+
def clean_all(immediate: bool = False, ignore_config: bool = False):
1519
from reactpy_django.config import (
1620
REACTPY_CLEAN_SESSIONS,
1721
REACTPY_CLEAN_USER_DATA,
@@ -20,12 +24,13 @@ def clean_all(immediate: bool = False, ignore_config=False):
2024

2125
config = Config.load()
2226
if immediate or is_clean_needed(config):
27+
config.cleaned_at = timezone.now()
28+
config.save()
29+
2330
if ignore_config or REACTPY_CLEAN_SESSIONS:
2431
clean_sessions()
2532
if ignore_config or REACTPY_CLEAN_USER_DATA:
2633
clean_user_data()
27-
config.cleaned_at = timezone.now()
28-
config.save()
2934

3035

3136
def clean_sessions():
@@ -65,14 +70,21 @@ def clean_user_data():
6570

6671

6772
def is_clean_needed(config: Config | None = None) -> bool:
68-
from reactpy_django.config import REACTPY_SESSION_MAX_AGE
73+
"""Check if a clean is needed. This function avoids unnecessary database reads by caching the
74+
CLEAN_NEEDED_BY date."""
75+
from reactpy_django.config import REACTPY_CLEAN_INTERVAL
6976
from reactpy_django.models import Config
7077

71-
config = config or Config.load()
72-
cleaned_at = config.cleaned_at
73-
clean_needed_by = cleaned_at + timedelta(seconds=REACTPY_SESSION_MAX_AGE)
78+
global CLEAN_NEEDED_BY
79+
80+
if REACTPY_CLEAN_INTERVAL == 0:
81+
return False
82+
83+
if CLEAN_NEEDED_BY.year == 1 or timezone.now() >= CLEAN_NEEDED_BY:
84+
config = config or Config.load()
85+
CLEAN_NEEDED_BY = config.cleaned_at + timedelta(seconds=REACTPY_CLEAN_INTERVAL)
7486

75-
return timezone.now() >= clean_needed_by
87+
return timezone.now() >= CLEAN_NEEDED_BY
7688

7789

7890
def inspect_clean_duration(start_time: datetime, task_name: str):

0 commit comments

Comments
 (0)