关于为什么会发生此错误,其他答案并不完全正确。 Dropbox 存储对象后端使用 django 实用程序(django.utils._os.safe_join) 来验证目标操作系统的文件名。见代码here
即使你传递了upload_to 参数,它给出了一个 unix 风格的路径(类似于 /save/path),django 实用程序确保该保存路径的根与操作系统的基本路径匹配:(。 dropbox SDK 不喜欢以所需保存路径为前缀的驱动器(AKA C:/path/file.name 不是 dropbox 的有效保存目录)。
要使这项工作在 Windows 上运行,请确保您做几件事
首先,像这样修改存储后端_full_path方法(或创建自己的子类)。
def _full_path(self, name):
if name == '/':
name = ''
print('Root path in dropbox.storage : ', self.root_path)
# If the machine is windows do not append the drive letter to file path
if os.name == 'nt':
final_path = os.path.join(self.root_path, name).replace('\\', '/')
# Separator on linux system
sep = '//'
base_path = self.root_path
if (not os.path.normcase(final_path).startswith(os.path.normcase(base_path + sep)) and
os.path.normcase(final_path) != os.path.normcase(base_path) and
os.path.dirname(os.path.normcase(base_path)) != os.path.normcase(base_path)):
raise SuspiciousFileOperation(
'The joined path ({}) is located outside of the base path '
'component ({})'.format(final_path, base_path))
# TODO Testing
print('Full file path in storage.dropbox._full_path : ', final_path)
return final_path
else:
return safe_join(self.root_path, name).replace('\\', '/')
其次,确保将内容和名称传递给模型 FileField。当我没有明确传递文件内容和名称时(关于上传的文件上下文保留文件名的问题?),我遇到了麻烦。我像这样重新实现了我的模型保存方法
def save(self, *args, **kwargs):
# Save file
## Save raw entry from user ##
# Extract files contents
try:
uploaded_raw_entry = kwargs['upload_raw_entry']
except KeyError:
raise UploadError(('No file was passed from the admin interface. ' +
'Make sure a ContentFile was passed when calling this models save method'))
# Test raw_directory_path TODO Remove after testing
print('Raw entry name from model.save : ', raw_directory_path(self, uploaded_raw_entry.name))
with uploaded_raw_entry.open(mode='rb') as f:
raw_entry_content = f.read()
raw_entry_file = ContentFile(content=raw_entry_content.encode('utf-8'),
name=raw_directory_path(self, uploaded_raw_entry.name))
# Save the content file into a model field
raw_entry_file.open(mode='rb')
self.raw_entry.save(raw_entry_file.name, raw_entry_file, save=False)
raw_entry_file.close()
这绝对可以在 Windows 上使用,但需要额外的步骤 :)