Skip to main content
 首页 » 编程设计

python之通过 Django 中的 View 提供静态文件

2024年08月12日45webabcd

我正在编写一个 Django 应用程序,让您在满足某些要求(例如,您必须登录)后下载文件。否则该文件需要不可访问。

无法通过 Apache 提供文件:我必须检查数据库中的用户权限。此外,无权更改我的 Apache 配置。

所以我想在Django中读取文件,然后设置合适的headers发送给客户端。

我使用了 this 上的信息Django 手册中有关 header 的页面。

我有以下代码:

#<- check persmissons here, continue if allowed -> 
 
#read the pdf file 
location = 'file.pdf' 
file = open(location, 'r') 
content = file.read() 
file.close 
 
#serve the file 
response = HttpResponse(content, mimetype='application/pdf') 
response['Content-Disposition'] = 'attachment; filename=filename.pdf' 
 
return response 

但是,下载的文件似乎已损坏:无法在 Adob​​e Reader 中打开。 我在想这可能是一些编码问题,但我想不通。

感谢任何帮助:)

请您参考如下方法:

您必须以二进制模式open() 文件(考虑docs)。

就像这样:

file = open(location, 'rb') 

我不知道它是否适用于您(因为您不允许更改 Apache 的设置),但我建议使用 Lighttpd + mod_secdownload出于性能原因。这个优雅的解决方案利用 Lighttpd 的优化来提供静态内容,同时将授权决策委托(delegate)给第 3 方(在您的情况下是 Django)。