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
# -*- 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
7,vim szgd/urls.py