当我在本地提供媒体服务并且需要处理获取文件内容的任务时,这非常简单。但是,我只是转移到了 django-storages,这并不是替代品。有人可以为我提供一种将文档从 S3 中提取出来的方法,以便我可以处理它。
老办法:
filename = settings.MEDIA_ROOT + "/" + document.name
xlsx = XLSXParser(filename = filename, uniq_header_column='XYX')
但是我转移到 django-storages 并且这(显然)不起作用。如何从 s3 中提取文件的本地副本来处理它。我以为我可以简单地这样做:
新(失败)方式:
filename = settings.MEDIA_ROOT + "/" + document.name
if not os.path.isfile(filename):
new_filename = tempfile.NamedTemporaryFile(delete=False)
new_filename.write(document.read())
filename = new_filename
xlsx = XLSXParser(filename = filename, uniq_header_column='XYX')
但是我不能在它爆炸时对此进行 read() 。
Traceback (most recent call last):
File ".../celery/task/trace.py", line 212, in trace_task
R = retval = fun(*args, **kwargs)
File ".../tasks.py", line 63, in process_homes
process_homes_non_task(**kwargs)
File ".../tasks.py", line 33, in process_homes_non_task
new_filename.write(document.read())
File ".../django/core/files/utils.py", line 16, in <lambda>
read = property(lambda self: self.file.read)
File ".../django/db/models/fields/files.py", line 46, in _get_file
self._file = self.storage.open(self.name, 'rb')
AttributeError: 'FieldFile' object has no attribute 'storage'
最后,我需要它同时适用于旧方式和新方式。显然我有点想多了..
更新:
遵循文档也无济于事。
filename = settings.MEDIA_ROOT + "/" + document.name
if not os.path.isfile(filename):
from django.core.files.storage import default_storage
s3_file = default_storage.open(document.name, 'rb')
new_filename = tempfile.NamedTemporaryFile(delete=False)
new_filename.write(s3_file.read())
filename = new_filename
xlsx = XLSXParser(filename = filename, uniq_header_column='Lot_Number')
xlsx.load_workbook_and_sheet()
谢谢您的帮助。