在访问django后端下载接口,直接下载数据,不在后端保存表格
# views.py
def download_csv_func(response_data_df, request_data, types=''):
response = HttpResponse(content_type='text/csv') # 指明下载的文件为csv格式
response.write(codecs.BOM_UTF8) # 指定编码类型
now_time = re.sub(':|-', '', str(datetime.datetime.now())).split('.')[0]
now_time = now_time.replace(' ', '_')
filename = "download_" + types + '_' + str(request_data.get("data1")) + '_' + now_time + ".csv"
# 指定下载的文件名
response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
columns = response_data_df.columns.values # 获取表头
values = response_data_df.values # 获取内容
writer = csv.writer(response)
writer.writerow(columns)
writer.writerows(values)
return response
def deal_request_data(req):
if req.method == 'GET':
data1 = req.GET.get("data1 ", None)
data2 = req.GET.get("data2 ", None)
else:
data1 = req.data.get("data1 ", None)
data2 = req.data.get("data2 ", None)
data = {'data1 ': data1 , 'data2 ': data2}
return data
class DownloadData(ModelViewSet):
def get_csv_result(self, request):
# 处理get或者post请求参数
request_data = deal_request_data(request)
# 从数据库提取数据
response_data_list = get_dataset(request_data) # (文章无此函数)
if response_data_list:
# 处理成pandas格式数据,函数是处理数据的
response_data_df = get_data_df(response_data_list) # (文章无此函数)
else:
response_data_df = DataFrame([])
# 保存生成缓存数据
response = download_csv_func(response_data_df, request_data, 'all_data')
return response
# urls.py
url(r'^tests/get_csv$',
views.DownloadData.as_view({'get': 'get_csv_result','post':'get_csv_result'})),
GET请求: http://127.0.0.1:5012/tests/get_csv?data1=***&data2=***
POST请求:http://127.0.0.1:5012/tests/get_csv
data: {
"data1":***,
"data2":***
}