Sar*_*ius 5 django sftp django-storage python-django-storages
我正在尝试使用 django-storages使用 SFTP访问我的“Hetzner”存储盒( https://www.hetzner.com/storage/storage-box),它应该保存媒体数据,即我的网站用户可以访问的图像文件动态上传。
我的文件的相应部分settings.py如下所示:
DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage'
SFTP_STORAGE_HOST = 'username.your-storagebox.de'
SFTP_STORAGE_ROOT = '/media'
SFTP_STORAGE_PARAMS = {
'username': 'username',
'password': 'password',
'allow_agent': False,
'look_for_keys': False,
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,当用户上传图像时,它被放置在存储空间上,我可以使用 SFTP 确认。但从存储盒获取图像失败,没有图像显示。控制台摘录:
[03/Sep/2021 22:34:01] "GET /media/filename.jpg HTTP/1.1" 404 1962
Run Code Online (Sandbox Code Playgroud)
我可以发现 Django 仍在我的内部查找MEDIA_DIR文件。再次,我的设置的相应部分:
MEDIA_DIR = 'media'
MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_DIR)
MEDIA_URL = '/media/'
Run Code Online (Sandbox Code Playgroud)
简而言之:使用 SFTP 似乎可以将文件存储到存储中,但再次获取它们却失败了。
编辑:根据要求,我将提供更多代码片段
models.py::
class SizeRestrictedImageField(ImageField):
def __init__(self, *args, **kwargs):
self.max_upload_size = kwargs.pop('max_upload_size', 0)
super().__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
data = super().clean(*args, **kwargs)
file = data.file
try:
if file.size > self.max_upload_size:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s'
) % (filesizeformat(self.max_upload_size),
filesizeformat(file.size)))
except AttributeError:
logger.exception('An Exception occured while checking for max size of image upload. size: `%s`'
, file.size)
pass
return data
class ImageModel(models.Model):
image = SizeRestrictedImageField(upload_to=POST_PIC_FOLDER, null=True, blank=True,
help_text="Erlaubte Dateitypen: .jpeg, .jpg, .png, .gif", max_upload_size=MAX_IMAGE_SIZE)
Run Code Online (Sandbox Code Playgroud)
和我的urls.py:
urlpatterns = [
path('defaultsite/', defaultsite_view, name='home'),
path('help', help_view, name="help"),
path('user/', include('user.urls')),
path('sowi/', include('sowi.urls')),
path('blog/', include('blog.urls')),
path('chat/', include('chat.urls')),
path('notifications/', include('notifications.urls')),
path('cookies/', include('cookie_consent.urls')),
path('', home_view, name="home"),
path('about/', AboutUsView.as_view(), name="about-us"),
path('impressum/', impressum_view, name="imprint"),
path('privacy/', privacy_view, name='privacy'),
path('privacy/statement/', privacy_statement_view, name='privacy-statement'),
path('agb', agb_view, name="agb")
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Run Code Online (Sandbox Code Playgroud)
我尝试+static(...)从我的网址模式中删除 - 部分,但这似乎并没有解决问题。
我想完成@Paulos 的回答。您可以使用中间件创建代理。创建一个文件project/middleware.py并将其添加middleware到settings.py.
然后创建中间件:
import mimetypes
from storages.backends.sftpstorage import SFTPStorage
from django.http import HttpResponse
class SFTPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
SFS = SFTPStorage()
response = self.get_response(request)
path = request.get_full_path()
if SFS.exists(path):
file = SFS._read(path)
type, encoding = mimetypes.guess_type(path)
response = HttpResponse(file, content_type=type)
response['Content-Disposition'] = u'attachment; filename="{filename}"'.format(filename=path)
return response
Run Code Online (Sandbox Code Playgroud)
编辑:实际上没有必要在每次调用时都打开一个新连接。ready()您应该在系统启动时在您的 -hook中创建一个连接config.py并使用这个连接。
| 归档时间: |
|
| 查看次数: |
1839 次 |
| 最近记录: |