Skip to content

Commit 9455fa4

Browse files
authored
Merge pull request #404 from qiniu/features/add-decode-except
Features/add decode except
2 parents c1bfdf8 + 1bf7b81 commit 9455fa4

File tree

4 files changed

+33
-6
lines changed

4 files changed

+33
-6
lines changed

qiniu/http.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# -*- coding: utf-8 -*-
2+
import logging
23
import platform
34

45
import requests
@@ -23,8 +24,10 @@ def __return_wrapper(resp):
2324
if resp.status_code != 200 or resp.headers.get('X-Reqid') is None:
2425
return None, ResponseInfo(resp)
2526
resp.encoding = 'utf-8'
26-
ret = resp.json() if resp.text != '' else {}
27-
if ret is None: # json null
27+
try:
28+
ret = resp.json()
29+
except ValueError:
30+
logging.debug("response body decode error: %s" % resp.text)
2831
ret = {}
2932
return ret, ResponseInfo(resp)
3033

qiniu/region.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,7 @@
1111

1212
class Region(object):
1313
"""七牛上传区域类
14-
1514
该类主要内容上传区域地址。
16-
1715
"""
1816

1917
def __init__(

qiniu/services/storage/upload_progress_recorder.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,15 @@ def get_upload_record(self, file_name, key):
3636
upload_record_file_path = os.path.join(self.record_folder, record_file_name)
3737
if not os.path.isfile(upload_record_file_path):
3838
return None
39-
with open(upload_record_file_path, 'r') as f:
40-
json_data = json.load(f)
39+
try:
40+
with open(upload_record_file_path, 'r') as f:
41+
try:
42+
json_data = json.load(f)
43+
except ValueError:
44+
json_data = None
45+
except IOError:
46+
json_data = None
47+
4148
return json_data
4249

4350
def set_upload_record(self, file_name, key, data):

test_qiniu.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121

2222
from qiniu.services.storage.uploader import _form_put
2323

24+
from qiniu.http import __return_wrapper as return_wrapper
25+
2426
import qiniu.config
2527

2628
if is_py2:
@@ -75,6 +77,23 @@ def is_travis():
7577
return os.environ['QINIU_TEST_ENV'] == 'travis'
7678

7779

80+
class HttpTest(unittest.TestCase):
81+
def test_json_decode_error(self):
82+
def mock_res():
83+
r = requests.Response()
84+
r.status_code = 200
85+
r.headers.__setitem__('X-Reqid', 'mockedReqid')
86+
87+
def json_func():
88+
raise ValueError('%s: line %d column %d (char %d)' % ('Expecting value', 0, 0, 0))
89+
r.json = json_func
90+
91+
return r
92+
mocked_res = mock_res()
93+
ret, _ = return_wrapper(mocked_res)
94+
assert ret == {}
95+
96+
7897
class UtilsTest(unittest.TestCase):
7998
def test_urlsafe(self):
8099
a = 'hello\x96'

0 commit comments

Comments
 (0)