简体   繁体   English

如何在 django 模板中显示来自 sftp 远程服务器的图像文件?

[英]How to display image file from sftp remote server in django template?

  1. We have 2 servers.我们有 2 台服务器。 One of them is for media files and the other one is for django project server(ngnx+gunicorne).其中一个用于媒体文件,另一个用于 django 项目服务器(ngnx+gunicorne)。
  2. Our media server is local(internal).我们的媒体服务器是本地(内部)。 We want to access to media server from inside the project with sftp storage package which includes paramiko.我们希望使用包含 paramiko 的 sftp 存储 package 从项目内部访问媒体服务器。 we don't want to access media server via URL (http,https).我们不想通过 URL (http,https) 访问媒体服务器。
  3. HttpResponse(file, content_type=type) can display the image file as a big picture but we want to pass the image file to django template for display in html file like <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a> HttpResponse(file, content_type=type)可以将图像文件显示为大图,但我们希望将图像文件传递给 django 模板,以便在 html 文件中显示,例如<a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a>
  4. We know HttpResponse is not a good solution but we use it below code for explained our problem.我们知道 HttpResponse 不是一个好的解决方案,但我们在下面的代码中使用它来解释我们的问题。
# view
def coursesPageView(request):
    courses = Course.objects.filter(is_published=True)
    image_data =[imageRespone(data) for data in courses]

    data = {
            'published_courses_list':courses,
            'images' : image_data
        }
    return render(request, 'pages/course2.html', data)
    

def imageRespone(valid_image):
    if sfs.exists(valid_image.image.name):
        file = sfs._read(valid_image.image.name)
        type, encoding = mimetypes.guess_type(valid_image.image.name)        
        response = HttpResponse(file, content_type=type)
        return response
    else:
        return HttpResponse('404 Not Found')
#course2.html
 <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a>

What you can do is mounting a shared drive into your webserver pointing to your media server (Samba for linux).您可以做的是将共享驱动器安装到指向您的媒体服务器(Samba for linux)的网络服务器中。 Then with Django you can specify the localisation of your statics file.然后使用 Django 您可以指定静态文件的本地化。

For example:例如:

import os

MEDIA_URL        = "/media/"
MEDIA_ROOT       = os.path.abspath(os.path.join(os.sep, 'srv', 'media'))

STATIC_URL       = '/app/static/'
STATIC_ROOT      = os.path.abspath(os.path.join(os.sep, 'srv', 'static'))

Pay attention to the permissions between the web server and the mounted folder.注意web服务器和挂载文件夹之间的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM