如何使用django-storage sftp下载文件? [英] How to download file using django-storage sftp?

查看:99
本文介绍了如何使用django-storage sftp下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django存储模块使用sftp将文件存储在某个位置,现在我们需要从sftp下载相同的文件。

I'm using django storage module to store file in a location using sftp and now we need to download same file from sftp.

有什么建议吗?

models.py

models.py

from storages.backends.sftpstorage import SFTPStorage
SFS = SFTPStorage()

class Configurations(BaseModel):
name = models.CharField(max_length=150, unique=True)
file = models.FileField(upload_to='configurations', storage=SFS)
descriptions = models.TextField(null=True, blank=True)

settings.py

settings.py

DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage'

SFTP_STORAGE_HOST = '127.0.0.1'
SFTP_STORAGE_ROOT = '/var/www/media/'
SFTP_STORAGE_PARAMS = {
    'username': 'root',
    'password': 'password',
    'allow_agent': False,
    'look_for_keys': False,
}
# SFTP_KNOWN_HOST_FILE = '~/.ssh/known_hosts'
SFTP_STORAGE_INTERACTIVE = False

views.py

from django.http import Http404

from rest_framework import viewsets
from rest_framework.parsers import MultiPartParser, FormParser

from .models import (CustomConfigurations)
from .serializers import (CustomConfigurationsSerializers)


class ToolCustomConfigurationsViewSet(viewsets.ModelViewSet):
    queryset = CustomConfigurations.objects.all()
    parser_classes = (FormParser, MultiPartParser,)
    serializer_class = CustomConfigurationsSerializers

    def get_queryset(self):
        queryset = self.queryset.all().order_by('-id')
        return queryset

serializer.py

serializer.py

class CustomConfigurationsSerializers(serializers.ModelSerializer):
class Meta:
    model = CustomConfigurations
    fields = '__all__'


推荐答案

这是我的解决方案:

@action(methods=['get'], detail=True)
def download(self, request, pk=None):

    try:
        obj = CustomConfigurations.objects.get(id=pk)
    except CustomConfigurations.DoesNotExist:
        raise Http404

    if SFS.exists(obj.file.name):
        file = SFS._read(obj.file.name)
        type, encoding = mimetypes.guess_type(obj.file.name)
        response = HttpResponse(file, content_type=type)
        response['Content-Disposition'] = u'attachment; filename="{filename}'.format(
            filename=obj.file.name)
        return response
    raise Http404

这篇关于如何使用django-storage sftp下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆