在我的Django应用程序中,我希望在用户删除帐户的4-5天后删除用户的媒体文件(他们的配置文件、图片和其他图像)。
def delete_files(sender, instance, **kwargs):
path = str(os.getcwd())
try:
pathdl = f"{path}\\data\\media\\{instance.username}"
shutil.rmtree(pathdl)
except Exception:
print(Exception)
post_delete.connect(delete_files, sender=User)我使用post_delete删除用户的文件,但是如何在4-5天或一定的时间内删除该文件。
发布于 2020-04-13 06:50:41
使用django-芹菜节拍来执行定期任务是很好的:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers。
以此为例
将此视为您的用户models.py。这里您需要的是一个到期字段,在删除它之前,将由cronjob检查它。
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 hereviews.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())当然,你也可以把这个想法融入到你想要解决这个问题的任何方式中。
https://stackoverflow.com/questions/61182248
复制相似问题