django搭建下载页面

1,安装pytz和django

2,django-admin startproject szgd

django-admin startapp chatlog

mkdir template

3,vim szgd/setting.py

.....

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chatlog',
]

......

 

4,vim chatlog/forms.py

from django import forms
import datetime

max_date = int(datetime.datetime.now().strftime('%Y%m%d'))
 
class AddForm(forms.Form):
开始时间= forms.IntegerField(min_value=20180201, max_value=max_date)
结束时间 = forms.IntegerField(min_value=20180201, max_value=max_date)
 
5,vim chatlog/views.py

# -*- coding=utf-8 -*-
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.http import FileResponse
from .forms import AddForm
import os
import shutil

def index(request):
file_dir = '/data/chatlog'
file_dir2 = '/tmp/chatlog'
if os.path.isdir(file_dir2):
shutil.rmtree(file_dir2)
os.mkdir(file_dir2)
else:
os.mkdir(file_dir2)
if request.method == 'POST':# 当提交表单时
form = AddForm(request.POST) # form 包含提交的数据
if form.is_valid():# 如果提交的数据合法
a = form.cleaned_data['开始时间']
b = form.cleaned_data['结束时间']
os.chdir(file_dir)
count_log_name = str(a) + '-' + str(b) + '.log'
count_log_file = os.path.join(file_dir2,count_log_name)
logfile_list = [ x for x in os.listdir(file_dir) if a <= int(x.strip('.log')) <= b]
with open(count_log_file,'w') as write_file:
for file in logfile_list:
with open(file,'r') as read_file:
if int(file.strip('.log')) == a:
write_file.write(read_file.read())
else:
write_file.write('\n' + read_file.read())
file = open(count_log_file,'rb')
response = FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="{}"'.format(count_log_name)
return response

else:# 当正常访问时
form = AddForm()
return render(request, 'index.html', {'haha': form})

6,vim template/index.html

<form method='post'>
{% csrf_token %}
{{ haha }}
<input type="submit" value="确定">
</form>

7,vim szgd/urls.py

 

 

转载于:https://www.cnblogs.com/zhuoyanXiaNa/p/11074869.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值