使用Django和Celery写入文件的问题

zi8p0yeb  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(124)

bounty还有6天到期,回答此问题可获得+50声望奖励,Oleg Klimenko希望引起更多关注此问题:它看起来像一个重要的bug。

我有这样一个模型来表示我的系统中的帖子。

class Post(models.Model):
    caption = models.CharField(max_length=256)
    text = models.CharField(max_length=256, null=True, blank=True)
    date_posted = models.DateTimeField(null=True, blank=True)
    source = models.ForeignKey(Source, on_delete=models.CASCADE)
    source_url = models.URLField()
    image = models.ImageField(upload_to='post_images', null=True)

我有一个数据收集器,它会抓取数据并将其放入这个模型中。插入抓取的单个记录的方法如下所示:

@staticmethod
def _load_post(post: CollectedPostData, source: Source) -> None:
    print('#' * 70)
    print(source)

    post_obj, created = Post.objects.get_or_create(
        caption=post.caption,
        text=post.text,
        source=source,
        source_url=post.source_url,
        date_posted=parse(post.date_posted) if post.date_posted else None,
    )

    print(post_obj, created)
    print(post.image)

    if created:
        print('CREATED')
        image_content = requests.get(post.image, allow_redirects=True).content
        print(len(image_content))
        post_obj.image.save(post.image, ContentFile(image_content), save=True)

        print('After SAVE')
    print('#' * 70)

当我用Celery运行代码时,我看到所有的print语句都被执行了,日志中没有问题,所有的Post对象都是用正确的数据创建的,但是'media'中的'post_images'文件夹没有创建,并且创建了零个文件...
有趣的是,当我运行这个手动剪切的代码时,所有的文件都被创建了...
我已经玩了好几天了,还是不明白为什么它不起作用。有人能帮帮我吗?
我正在使用:

  • Django==4.1.7
  • 枕头==9.4.0
  • Redis==4.5.3
vmdwslir

vmdwslir1#

解决方案如下:Saving File in Model in View works but not in Celery Task
(c)我发现了这个问题。整个应用程序都在Docker环境中运行。Django应用程序和Celery在不同的容器中运行。问题是Celery无法访问Django文件系统,所以文件被保存,但无法访问Django容器......非常愚蠢的错误,但我花了几天时间才弄清楚。所以如果有人遇到同样的问题,请检查您的Docker卷。

相关问题