如何在django媒体文件中创建目录(最好的方法)?

时间:2016-07-23 08:52:02

标签: python django urllib file-not-found

我想将下载的图像保存到类似的路径:media / images / [user.pk] /直接来自urllib库的urlretrieve是可能的,最优雅的方式是什么?

这是使用过的代码段:

  • 这里我使用的urlretrieve路径如... / media / images / [user.pk] / [filename.jpg]

    file_path, header = urlretrieve(image_url, os.path.join(
                        MEDIA_ROOT, get_image_path(
                           self, 'profile_image_'+str(
                             datetime.utcnow().strftime("%Y%m%d_%H%M"))+'.jpg
    
  • 这是定义的函数,它返回文件名为

    的所需路径
    def get_image_path(instance, filename):
        return os.path.join('images', str(instance.pk), filename)
    

当我运行时,由于文件不存在,我收到错误:

/ rest / oauth2 / google中的FileNotFoundError [Errno 2]没有这样的文件或目录:'C:\ xampp \ htdocs \ BookProjectFresh \ media \ images \ 21 \ profile_image_20160723_0801.jpg'

我知道我可以通过首先将文件加载到temp文件夹然后从那里加载并放入django模型来实现它,如果它不存在它将自动创建文件路径,但是我在我的电脑上有2个文件相同的内容。或者是os.path.makedirs最好的方法吗?如果您知道其他任何方式,请分享。

1 个答案:

答案 0 :(得分:0)

我解决了这样的问题:

def save_image_from_url(self, image_url):
        if self.profile_image_url  != image_url or not os.path.isfile(self.profile_image.path):
            if not os.path.exists(get_image_path(self, os.path.join(MEDIA_ROOT, get_image_path(
                self, '')))):
                os.makedirs(get_image_path(self, os.path.join(MEDIA_ROOT, get_image_path(
                self, ''))))

            self.profile_image_url = image_url

            file_path, header = urlretrieve(image_url, os.path.join(MEDIA_ROOT, get_image_path(
                self, 'profile_image_'+str(datetime.utcnow().strftime("%Y%m%d_%H%M"))+'.jpg')))

            self.profile_image = file_path
            self.save()