Django sendfile下载 - 找不到页面

时间:2014-06-20 13:42:08

标签: python django download

我使用Django sendfile模块向用户提供文件。文档:

https://github.com/johnsensible/django-sendfile

我使用了简单的后端。更确切地说,我将SENDFILE_BACKEND = 'sendfile.backends.simple'放在settings.py

我已检查过并检查过文件是否在那里。这是我的代码(我认为只有请求函数是相关的,但我包括整个函数,因为我在pk中使用urls.py):

def permit(request, pk)
    if int(request.user.id) == int(pk) and int(request.user.id) >= 1:
        return sendfile(request, request.path)
    else:
        return render_to_response('forbidden.html')
    return HttpResponseRedirect('/notendur/list')

user是一个Django User对象。 pk是取自urls.py的正则表达式。 我得到的错误是

404: [path to file] does not exist.

这是project/urls.py中的相关条目:

url(r'^media/uploads/(?P<pk>[^/]+)', 'notendur.views.permit')

如您所见,如果regx匹配,urls.py会将用户重定向到permit函数。如果用户的ID等于目录名称(我按用户ID命名目录),则允许用户下载文件,否则不允许。

我已经确认此错误是由sendfile模块引起的,因为如果我直接提供文件,没有sendfile模块,下载工作正常。

1 个答案:

答案 0 :(得分:1)

首先是一个很大的警告,你正在做的事情是危险的。您信任您的用户为您提供路径。你必须经常消毒这个!

现在问题:不是将相关文件提供给当前目录,最好根据设置文件中设置的某些根媒体路径提供绝对文件,然后执行:

sanitized_path = sanitize(request.path) # you'll have to write a sanitize function
media_path = "%s%s" (settings.MEDIA_ROOT, sanitized_path)
if not path.exists(media_path): # Don't trust your visitors too much!
   # raise 404
return sendfile(request, media_path)