我有两个服务器的设置,其中一个运行Django Web服务器,另一个存储文件。我拥有Web服务器,但我只能以普通用户的身份访问存储服务器。
我希望用户可以直接从存储服务器使用Web界面下载文件。
将根据传递给视图的参数构建存储服务器上文件的路径。
我已经解决了使用Fabric下载文件的问题,我将发布我所做的答案,因为我认为更多的人可以从中受益,因为我没有找到关于这个特定问题的SO的另一个问题
但我想听听我的解决方案可能提出的意见和其他可能更好的解决方案或问题。此外,如果还有另一种方法可以使用除Fabric之外的其他工具。
答案 0 :(得分:0)
这是我目前用来解决问题的视图代码:
from django.http import HttpResponse
def download_file(request, remote_path):
from django.core.files.base import ContentFile
from fabric.api import env, get, execute
from mimetypes import guess_type
# This will be passed to Fabric's execute function
hosts = ['storage_server_IP']
# Setting the user and password of the remote server on Fabric environment
env.password = 'my_password'
env.user = 'my_user'
# Function to be executed on remote server
def get_file(remote_path):
from StringIO import StringIO
fb = StringIO()
get(remote_path, fb)
# This will return a string holding the file content
return fb.getvalue()
result_dict = execute(get_file, remote_path, hosts=hosts)
# The execute function returns a dict where the hosts are the keys and the return of the called function (get_file in this case) are the values, so we get only the value of our only host
content = result_dict[hosts[0]]
# Creates a file from the string that holds the content
my_file = ContentFile(content)
my_file.name = remote_path.split('/')[-1]
# This guesses the mime_type of the file, based on its extension
mime_type = guess_type(my_file.name)
response = HttpResponse(my_file, content_type=mime_type)
response['Content-Disposition'] = 'attachment; filename=' + my_file.name
return response