使用 API 删除文件夹或目录 (django)

Delete folder or directory using API (django)

我写了一个 Python 脚本来从文件目录中删除或删除文件夹。 代码如下:

import os
import sys
import shutil

base_dir = os.path.dirname(os.path.realpath(__file__))
path = 'media/user110'

try:
    path = os.path.join(base_dir, path)
    shutil.rmtree(path)
    print("Deleted: " + path)
except OSError as e:
    print("Error: %s - %s." % (e.filename, e.strerror))

这成功了。但它在 API 使用 Django 时不起作用。

如果我打印 path 它显示 '/home/Desktop/my_project/media/user110/

但是当我想在 API 中使用 Django 执行此操作时,使用相同的代码并打印 path 我得到 /media/user110/ 并且它抛出一个异常说 this directory doesn't exist

现在我想使用 API 删除或删除文件目录。我想要解决方案。

顺便说一句,我正在使用 Linux,我的项目将部署在 Linux 服务器中。

使用下面的代码片段删除文件夹非常简单。

import shutil
import os
from main_app.settings import BASE_DIR

# This is your folder path
file_location = os.path.join(BASE_DIR, 'media/user110')

# Here, lets delete the file
shutil.rmtree(file_location, ignore_errors = False)
# making ignore_errors = True will not raise a FileNotFoundError