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

 

 

posted on 2019-06-23 23:18  灼眼者  阅读(201)  评论(0编辑  收藏  举报