我试图创建一个系统,允许管理员上传一个zipfile,然后脚本将自动使用signals,解压缩它,搜索jpg,png中的所有文件。创建它们的list,并根据它生成数据库记录。在
在模型中,我有Project和Photo表,Photo与Many-to-One即Foreign Key的关系。在
下面的脚本是我正在工作的信号。我可以得到instance.file_zip.path而没有错误,并且脚本在手动运行时运行良好。在
长时间的调试,我假设belongs_to=instance有问题,但我不知道如何修复它,因为我实际上不明白它为什么会出错。
提取部分工作得很好,我只是把它们放在这里作为参考,很可能你不需要阅读和理解它。在@receiver(post_save, sender=Project)
def unzip_and_process(sender, instance, **kwargs):
#project_zip = FieldFile.open(file_zip, mode='rb')
file_path = instance.file_zip.path
file_list = []
with zipfile.ZipFile(file_path, 'r') as project_zip:
project_zip.extractall(re.search('[^\s]+(?=\.zip)', file_path).group(0))
project_zip.close()
for root, dirs, files in os.walk(file_path):
for filename in files:
file_list.append(os.path.join(root, filename))
photo_list = filter(filter_photos, file_list)
for photo in photo_list:
print 'Processing %s'%photo
p = Photo.objects.create(belongs_to=instance, img=photo, desc='Processed from zipfile')
p.save()
更新
^{pr2}$