1
+ from __future__ import annotations
2
+
1
3
import logging
2
4
from datetime import datetime , timedelta
3
5
from typing import TYPE_CHECKING
10
12
if TYPE_CHECKING :
11
13
from reactpy_django .models import Config
12
14
15
+ CLEAN_NEEDED_BY : datetime = datetime (year = 1 , month = 1 , day = 1 )
16
+
13
17
14
- def clean_all (immediate : bool = False , ignore_config = False ):
18
+ def clean_all (immediate : bool = False , ignore_config : bool = False ):
15
19
from reactpy_django .config import (
16
20
REACTPY_CLEAN_SESSIONS ,
17
21
REACTPY_CLEAN_USER_DATA ,
@@ -20,12 +24,13 @@ def clean_all(immediate: bool = False, ignore_config=False):
20
24
21
25
config = Config .load ()
22
26
if immediate or is_clean_needed (config ):
27
+ config .cleaned_at = timezone .now ()
28
+ config .save ()
29
+
23
30
if ignore_config or REACTPY_CLEAN_SESSIONS :
24
31
clean_sessions ()
25
32
if ignore_config or REACTPY_CLEAN_USER_DATA :
26
33
clean_user_data ()
27
- config .cleaned_at = timezone .now ()
28
- config .save ()
29
34
30
35
31
36
def clean_sessions ():
@@ -65,14 +70,21 @@ def clean_user_data():
65
70
66
71
67
72
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
69
76
from reactpy_django .models import Config
70
77
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 )
74
86
75
- return timezone .now () >= clean_needed_by
87
+ return timezone .now () >= CLEAN_NEEDED_BY
76
88
77
89
78
90
def inspect_clean_duration (start_time : datetime , task_name : str ):
0 commit comments