在 Django 中删除用户几天后删除用户的文件

在我的 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 天或某个时间段后删除文件。


元芳怎么了
浏览 155回答 1
1回答

慕森卡

将 django-celery-beat 用于定期任务会很好:http: //docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers以此为例将此视为您的用户models.py。您在这里需要的是一个过期字段,cronjob 在删除它之前会对其进行检查。models.py&nbsp; &nbsp;class Foo(models.model):&nbsp; &nbsp; &nbsp; &nbsp;UserId= models.CharField(max_length=40, unique=True) #user pk here&nbsp; &nbsp; &nbsp; &nbsp;expiration_date = models.DateTimeField() # you would set the time hereviews.pyimport datetimefrom django.utils import timezonedef add_foo(instance):&nbsp; &nbsp; # Create an instance of foo with expiration date now + one day&nbsp; &nbsp; objects.create(expiration_date=timezone.now() + datetime.timedelta(days=1))&nbsp; &nbsp; &nbsp; &nbsp; path = str(os.getcwd())&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; pathdl = f"{path}\\data\\media\\{instance.username}"&nbsp; &nbsp; &nbsp; &nbsp; shutil.rmtree(pathdl)&nbsp; &nbsp; &nbsp; &nbsp; User.objects.create(expiration_date=timezone.now() + datetime.timedelta(days=1))&nbsp; &nbsp; except Exception:&nbsp; &nbsp; &nbsp; &nbsp; print(Exception)post_delete.connect(delete_files, sender=User)tasks.pyfrom celery.schedules import crontabfrom celery.task import periodic_taskfrom django.utils import timezone@periodic_task(run_every=crontab(minute='*/5'))def delete_old_foos():&nbsp; &nbsp; # Query all the expired date in our database&nbsp; &nbsp; userMedia = Users.objects.all()&nbsp; &nbsp; #Or get a specific user id to delete their file&nbsp; &nbsp; # Iterate through them&nbsp; &nbsp; for file in userMedia :&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; # If the expiration date is bigger than now delete it&nbsp; &nbsp; &nbsp; &nbsp; if file.expiration_date < timezone.now():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file.delete()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # log deletion&nbsp; &nbsp; return "completed deleting file at {}".format(timezone.now())当然,你也可以将这个想法融入到任何你想解决这个问题的方式中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python