php - 如何在 Django 中发送文件以响应?
问题描述
我有这样的 php 函数,我尝试在我的 Django 项目中重写。header()
对于和之类的 php 方法,python 中的类似物应该是什么show_error()
?另外如何发送文件以响应?
php:
function waprfile($date=false) {
if(!isset($date) || $date==false) $date = date("d.m.y");
$timestmp = date2timestamp($date);
$filepath = "https://www.example.com/files/".$this->lang_code."/";
if(file_get_contents($filepath.date("dmy",$timestmp).".xls"))
{
header("Location: ".$filepath."wapr".date("dmy",$timestmp).".xls");
}
else
{
show_error(_langWrite("No file for specified date", "Файл на указанную дату отсутствует"));
}
}
Python:
import urllib.request
import datatime
import time
from django.utils import translation
def isset(variable):
return variable in locals() or variable in globals()
def waprfile(request, date):
if(not isset(date) or date==False):
date = datetime.datetime.now().strftime('%d.%m.%Y')
timestmp = time.mktime(datatime.datetime.strptime(date, "%d.%m.%Y").timetuple())
filepath = "https://www.example.com/files/" + str(translation.get_language()) + "/"
formatted_date = datetime.datetime.fromtimestamp(timestmp).strftime('%d%m%y')
if(urllib.request.urlopen(filepath + formatted_date + '.xls')):
# What must be here?
else:
# What must be here?
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=' + fileName
return response
解决方案
首先读取文件,然后将其作为响应发送。
from django.http import HttpResponse, HttpResponseNotFound
def waprfile(request, date):
...
file_location = '/path/to/file/foo.xls'
try:
with open(file_location, 'r') as f:
file_data = f.read()
# sending response
response = HttpResponse(file_data, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="foo.xls"'
except IOError:
# handle file not exist case here
response = HttpResponseNotFound('<h1>File not exist</h1>')
return response
阅读文档以获取更多信息: 告诉浏览器将响应视为文件附件并返回错误
推荐阅读
- javascript - Javascript按值访问对象数组
- flutter - 在应用程序加载时多次调用 Flutter HTTP 请求
- r - 使用循环在 R 中创建多个混淆矩阵
- python - 将产生 BMI 和用户所属类别的函数
- android - 为什么 Android 无法识别“BillingClient”
- c++-cli - c++/cli 中的托管指针是否使用 GCRoot 自动初始化为 nullptr?
- ios - CoreML:异常 Espresso 异常:“无效状态”:空输出 blob
- reactjs - 解析器中的值未定义(Graphql、Apollo、React)
- java - 使用 EntityUtils.consume(httpEntity) 直到流结束消费如何导致将连接释放回连接池?
- python - 在数据框列的一系列 NaN 之后删除第一个值