0

我在使用 django-storages ( https://github.com/jschneier/django-storages ) 的 SFTP-API 时遇到了一个奇怪的问题。我正在尝试使用它来获取存储在不同服务器上的媒体文件,因此需要为 SFTP 下载创建代理,因为普通 Django 只是将 GET 请求发送到MEDIA_ROOT. 我认为中间件提供了一个很好的钩子:

import mimetypes

from storages.backends.sftpstorage import SFTPStorage
from django.http import HttpResponse



from storages.backends.sftpstorage import SFTPStorage

class SFTPMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response


    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        try:
            path = request.get_full_path()
            SFTP = SFTPStorage()  # <- this is where the magic happens

            if SFTP.exists(path):
                file = SFTP._read(path)

                type, encoding = mimetypes.guess_type(path)  
                response = HttpResponse(file, content_type=type)
                response['Content-Disposition'] = u'attachment; filename="{filename}"'.format(filename=path)
        except PermissionError:
            pass

        return response

这工作正常,但显然每次发出我不想要的网站调用时它都会打开一个新连接(它也会在 3 次重新加载或其他东西后崩溃,我认为到那时它必须有许多并行连接)。SFTP = SFTPStorage()因此,我尝试通过将-initialization 移动到__init__()仅调用一次的 -method 来通过 SFTP 打开一个与服务器的连接:

import mimetypes

from storages.backends.sftpstorage import SFTPStorage
from django.http import HttpResponse


from storages.backends.sftpstorage import SFTPStorage


class SFTPMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.SFTP = SFTPStorage() # <- this is where the magic happens


    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        try:
            path = request.get_full_path()


            if self.SFTP.exists(path):
                file = self.SFTP._read(path)

                type, encoding = mimetypes.guess_type(path)  
                response = HttpResponse(file, content_type=type)
                response['Content-Disposition'] = u'attachment; filename="{filename}"'.format(filename=path)
        except PermissionError:
            pass

        return response

但是这个实现似乎不起作用,程序在方法之前SFTP.exists()或之后卡住了SFTP._read()

谁能告诉我如何解决这个问题?或者有没有人对如何解决这个问题有更好的想法?

提前致谢, Kingrimursel

4

0 回答 0