From a084614af9d25e30ae4e7a18d34eee20bda72686 Mon Sep 17 00:00:00 2001 From: "sxw@401" Date: Sat, 12 Sep 2015 21:25:36 +0800 Subject: [PATCH] =?UTF-8?q?with=20open()=20=20as=20=E8=AF=AD=E5=8F=A5?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0try&except=EF=BC=8C=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problem/views.py | 9 ++++++--- utils/views.py | 14 ++++++++++---- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/problem/views.py b/problem/views.py index 5128313..94e3a7a 100644 --- a/problem/views.py +++ b/problem/views.py @@ -147,9 +147,12 @@ class TestCaseUploadAPIView(APIView): f = request.FILES["file"] tmp_zip = "/tmp/" + rand_str() + ".zip" - with open(tmp_zip, "wb") as test_case_zip: - for chunk in f: - test_case_zip.write(chunk) + try: + with open(tmp_zip, "wb") as test_case_zip: + for chunk in f: + test_case_zip.write(chunk) + except IOError: + return error_response(u"上传错误,写入临时目录失败") test_case_file = zipfile.ZipFile(tmp_zip, 'r') name_list = test_case_file.namelist() diff --git a/utils/views.py b/utils/views.py index af3afc9..87beeb4 100644 --- a/utils/views.py +++ b/utils/views.py @@ -18,10 +18,16 @@ class SimditorImageUploadAPIView(APIView): image_name = rand_str() + '.' + str(request.FILES["image"].name.split('.')[-1]) image_dir = settings.IMAGE_UPLOAD_DIR + image_name - with open(image_dir, "wb") as imageFile: - for chunk in img: - imageFile.write(chunk) + try: + with open(image_dir, "wb") as imageFile: + for chunk in img: + imageFile.write(chunk) + except IOError: + return Response(data={ + "success": True, + "msg": "上传错误", + "file_path": "/static/upload_image/" + image_name}) return Response(data={ "success": True, - "msg": "error message", + "msg": "", "file_path": "/static/upload_image/" + image_name})