non-automatic method
python manage.py clearsessions
The first method is a general method (using APScheduler to clear regularly)
install plugin
pip install apscheduler
Add a scheduled task
Find wsgi.py in the app folder with the same name as the project
Modify wsgi.py
Add the following code in wsgi.py
import os
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
# 定时任务, 清空session数据库,这个库不清的话,会不停的增大
#days为int值,几天一清理
#start_date开始日期
@scheduler.scheduled_job(trigger='interval', days=1,start_date='2022-05-02 20:08:00', id='clear_session')
def clear_session_job():
print('clear session data base')
# 命令行执行python manage.py clearsessions,可以清除已经失效的session
os.system('python manage.py clearsessions')
scheduler.start()
running result
Session in the database before running:
run:
clear session data base !!
Note: Warnings are not errors! !
Session in the database after running:
Obviously, all expired sessions are cleaned up
Finish
When running the django project in the future, expired sessions will be automatically cleared within the specified time every day
Using the plan panel (shell script) of the pagoda panel (baota)
Since my project is built on the server using Pagoda, I also use a lot of Pagoda's automation scripts to run and maintain my server
Enter the shell editing interface
Scheduled tasks -> task type (shell script) -> task name (named by yourself) -> execution cycle (set by yourself)
write shell script
#!/bin/sh
#cd manage.py所在的项目文件夹
cd /www/wwwroot/vedio
python3 manage.py clearsessions
execute script
running result
Session in the database before running: sixteen session data, six expired sessions
Execution log:
Session in the database after running: ten pieces of data, the expired ones have been deleted
Finish
When running the django project in the future, expired sessions will be automatically cleared within the specified time every day