簡體   English   中英

使用Fabric從遠程主機獲取文件並直接在Django視圖中提供文件

[英]Get file from remote host with Fabric and serve it directly in Django view

我有兩台服務器,其中一台運行Django Web服務器,另一台存儲文件。 我擁有Web服務器,但是我只有ssh身份才能以普通用戶的身份訪問存儲服務器。

我想讓用戶可以使用Web界面直接從存儲服務器下載文件。

存儲服務器上文件的路徑將基於傳遞給視圖的參數來構建。

我已經解決了使用Fabric下載文件的問題,我將發布所做的回答,因為我認為更多的人可以從中受益,因為我沒有找到解決該特定問題的其他問題。

但我想聽聽我的解決方案可能帶來的意見和其他可能更好的解決方案或問題。 另外,如果還有其他方法可以使用除Fabric之外的其他工具來執行此操作。

這是我當前用於解決問題的視圖的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM