【问题标题】:Delete a user's file after some days after the user is deleted in Django在 Django 中删除用户几天后删除用户的文件
【发布时间】:2020-07-25 16:17:53
【问题描述】:

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

【问题讨论】:

    标签: python django django-models django-admin django-signals


    【解决方案1】:

    将 django-celery-beat 用于定期任务会很好: 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 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())
    
    

    当然,您也可以将这个想法融入任何您想解决这个问题的方式中。

    【讨论】:

      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      相关资源
      最近更新 更多