1 回答

TA貢獻(xiàn)1806條經(jīng)驗 獲得超8個贊
將 django-celery-beat 用于定期任務(wù)會很好:http: //docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers
以此為例
將此視為您的用戶models.py。您在這里需要的是一個過期字段,cronjob 在刪除它之前會對其進(jìn)行檢查。
models.py
class Foo(models.model):
UserId= models.CharField(max_length=40, unique=True) #user pk here
expiration_date = models.DateTimeField() # you would set the time here
views.py
import datetime
from django.utils import timezone
def add_foo(instance):
# Create an instance of foo with expiration date now + one day
objects.create(expiration_date=timezone.now() + datetime.timedelta(days=1))
path = str(os.getcwd())
try:
pathdl = f"{path}\\data\\media\\{instance.username}"
shutil.rmtree(pathdl)
User.objects.create(expiration_date=timezone.now() + datetime.timedelta(days=1))
except Exception:
print(Exception)
post_delete.connect(delete_files, sender=User)
tasks.py
from celery.schedules import crontab
from celery.task import periodic_task
from django.utils import timezone
@periodic_task(run_every=crontab(minute='*/5'))
def delete_old_foos():
# Query all the expired date in our database
userMedia = Users.objects.all()
#Or get a specific user id to delete their file
# Iterate through them
for file in userMedia :
# If the expiration date is bigger than now delete it
if file.expiration_date < timezone.now():
file.delete()
# log deletion
return "completed deleting file at {}".format(timezone.now())
當(dāng)然,你也可以將這個想法融入到任何你想解決這個問題的方式中。
添加回答
舉報