0

我制作了一个简单的文件服务器,可以在我的树莓派(1/2 gb RAM,1 个 CPU)上运行。它在 nginx(1 个工作人员)后面的 gunicorn(3 个工作人员)下运行。

我有一个奇怪的问题,当我尝试同时下载太多文件(比如 5 个)时,它们都会部分通过然后中止。django 服务器没有输出(我也使用开发服务器遇到了这个问题,这就是为什么它现在在 gunicorn 和 nginx 后面运行,但仍然没有乐趣)。

我的下载视图是:

@never_cache
def download_media(request, user_id, session_key, id, filepath):
    "Download an individual media file"

    context = RequestContext(request)

    # validate the user_id & session_key pair
    if not __validate_session_key(user_id, session_key):
        return HttpResponseRedirect(reverse('handle_logout'))

    filepath = unicode(urllib.unquote(filepath))

    if '..' in filepath:
        raise SuspiciousOperation('Invalid characters in subdir parameter.')

    location = MediaCollectionLocation.objects.get(id=id)

    path = os.path.join(location.path, filepath)

    response = HttpResponse(FileWrapper(file(path)), content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(path)

    response['Content-Length'] = os.path.getsize(path)
    response["Cache-Control"] = "no-cache, no-store, must-revalidate"
    return response

我以这种方式提供文件是因为我希望客户端进行身份验证(所以不要只想用 nginx 重定向和提供静态内容)。

任何人都知道如果我同时提出多个请求,为什么它会退出?

4

1 回答 1

0

我不完全确定为什么文件会失败,但我想这与下载的文件多于工作人员有关,或者 nginx 和 gunicorn 之间发生超时。

只有在 django 对用户进行身份验证后,您才能让 nginx 提供文件,方法是让 django 设置一个特定的标头,然后 nginx 读取(仅限内部)并提供文件本身。

XSendFile是 nginx 用来执行此操作的。然后,您可以创建一些中间件或函数来从 django 设置适当的标头,或者使用django-sendfile之类的东西和 nginx 后端来为您完成所有工作。

If the issue you're experiencing is caused by a timeout between django and nginx, this fix should solve it. If it does not, increase the number of nginx workers as well, since it will be responsible for the serving of files now.

于 2013-02-25T01:42:11.783 回答