之前写了一个上传文件模块,但是当文件很大时就会挂掉,分析了一下,原来是我将文件所有数据先读到内存,然后再写入文件,这样极大占用了CPU资源。现改进了下:
def upload_file(request):
file_obj = request.FILES.get('file', None)
if file_obj:
str_time = time.strftime('%Y-%m-%d_%H:%M:%S',time.localtime(time.time()))
fname = file_obj.name;
fname = str_time + fname[fname.rfind('.'):]
of = open(UPLOAD_DIR+fname, 'wb+')
for chunk in file_obj.chunks():
of.write(chunk)
of.close()
return HttpResponseRedirect('/')