第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Django 中刪除用戶幾天后刪除用戶的文件

在 Django 中刪除用戶幾天后刪除用戶的文件

元芳怎么了 2022-10-06 16:53:30
在我的 Django 應(yīng)用程序中,我想在用戶刪除其帳戶 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)我曾經(jīng)post_delete刪除用戶的文件,但是如何在 4-5 天或某個時間段后刪除文件。
查看完整描述

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)然,你也可以將這個想法融入到任何你想解決這個問題的方式中。


查看完整回答
反對 回復(fù) 2022-10-06
  • 1 回答
  • 0 關(guān)注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號