使用nginx的Django sendfile无法将文件作为附件发送

时间:2017-12-30 03:02:15

标签: python django nginx x-sendfile

我正在使用django-sendfile将大文件作为附件发送到用户界面。这适用于sendfile.backends.simple后端,但是当我使用sendfile.backends.nginx时,它会在nginx日志上返回404错误。

我认为我的nginx配置有问题。

views.py

class FileDownloadView(View):
    def get(self, request, id_file):
        obj = FileCombined.objects.get(id_file=id_file)
        return sendfile(request, obj.path, attachment=True)

urls.py

from django.conf.urls import url
from django.urls import path

urlpatterns += [
    path(r'file/id/<str:id_file>/delete/', FileDeleteView.as_view(), name='files-delete'),
    path(r'file/id/<str:id_file>/download/', FileDownloadView.as_view(), name='files-download'),
    ]

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
SENDFILE_BACKEND = "sendfile.backends.nginx"
SENDFILE_ROOT = os.path.join(BASE_DIR, 'media')
SENDFILE_URL = '/media'

/etc/nignx/sites-enabled/myapp

server { # simple reverse-proxy
    listen       80;
    server_name  localhost;
    sendfile            on;

    # serve static files
    location /static {
       proxy_pass      http://127.0.0.1:8000/static;
    }

    location /media/ {
        internal;
        root  /home/foo/project/django-combine/media;
    }

    location / {
      proxy_pass      http://127.0.0.1:8000;
    }
}

nginx/access.log

127.0.0.1 - - [30/Dec/2017:08:20:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36"
127.0.0.1 - - [30/Dec/2017:08:25:01 +0530] "GET /file/id/5114a7721b6943fb31fc143a20adbec630bb5eb2516d7574b881454209338eed/download/ HTTP/1.1" 404 208 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/52.0.2743.116 Chrome/52.0.2743.116 Safari/537.36"

实际上我要下载的文件存在于/home/foo/project/django-combine/media目录中。

我的视图中存在

print(obj.path)

/home/foo/project/django-combine/media/google-oauth2|817468732648743/33601a74-de02-4b83-8587-1f8c3d8c96fb/output/combined.csv

1 个答案:

答案 0 :(得分:1)

您需要更改

root /home/foo/project/django-combine/media/;

root /home/foo/project/django-combine/; 

因为root中的/mediaroot /home/foo/project/django-combine/media/media的有效路径。

您甚至可以使用alias /home/foo/project/django-combine/media/;代替root /home/foo/project/django-combine/media/。那也行得通。至于别名,位置路径没有附加

此外,您需要确保没有像|那样的特殊符号,这使得nginx难以找到文件