1
1
# -*- coding: utf-8 -*-
2
2
import logging
3
- import os
4
3
import platform
5
- from datetime import datetime
6
4
7
5
import requests
6
+ from requests .adapters import HTTPAdapter
8
7
from requests .auth import AuthBase
9
8
10
- from qiniu .compat import is_py2 , is_py3
11
- from qiniu import config
9
+ from qiniu import config , __version__
12
10
import qiniu .auth
13
- from . import __version__
11
+
12
+ from .client import HTTPClient
13
+ from .response import ResponseInfo
14
+ from .middleware import UserAgentMiddleware
15
+
16
+
17
+ qn_http_client = HTTPClient (
18
+ middlewares = [
19
+ UserAgentMiddleware (__version__ )
20
+ ]
21
+ )
22
+
14
23
15
24
_sys_info = '{0}; {1}' .format (platform .system (), platform .machine ())
16
25
_python_ver = platform .python_version ()
22
31
_headers = {'User-Agent' : USER_AGENT }
23
32
24
33
25
- def __add_auth_headers (headers , auth ):
26
- x_qiniu_date = datetime .utcnow ().strftime ('%Y%m%dT%H%M%SZ' )
27
- if auth .disable_qiniu_timestamp_signature is not None :
28
- if not auth .disable_qiniu_timestamp_signature :
29
- headers ['X-Qiniu-Date' ] = x_qiniu_date
30
- elif os .getenv ('DISABLE_QINIU_TIMESTAMP_SIGNATURE' ):
31
- if os .getenv ('DISABLE_QINIU_TIMESTAMP_SIGNATURE' ).lower () != 'true' :
32
- headers ['X-Qiniu-Date' ] = x_qiniu_date
33
- else :
34
- headers ['X-Qiniu-Date' ] = x_qiniu_date
35
- return headers
36
-
37
-
38
34
def __return_wrapper (resp ):
39
35
if resp .status_code != 200 or resp .headers .get ('X-Reqid' ) is None :
40
36
return None , ResponseInfo (resp )
@@ -48,14 +44,15 @@ def __return_wrapper(resp):
48
44
49
45
50
46
def _init ():
51
- session = requests .Session ()
52
- adapter = requests .adapters .HTTPAdapter (
47
+ global _session
48
+ if _session is None :
49
+ _session = qn_http_client .session
50
+
51
+ adapter = HTTPAdapter (
53
52
pool_connections = config .get_default ('connection_pool' ),
54
53
pool_maxsize = config .get_default ('connection_pool' ),
55
54
max_retries = config .get_default ('connection_retries' ))
56
- session .mount ('http://' , adapter )
57
- global _session
58
- _session = session
55
+ _session .mount ('http://' , adapter )
59
56
60
57
61
58
def _post (url , data , files , auth , headers = None ):
@@ -170,18 +167,16 @@ def _post_with_qiniu_mac(url, data, auth):
170
167
qn_auth = qiniu .auth .QiniuMacRequestsAuth (
171
168
auth
172
169
) if auth is not None else None
173
- headers = __add_auth_headers ({}, auth )
174
170
175
- return _post (url , data , None , qn_auth , headers = headers )
171
+ return _post (url , data , None , qn_auth )
176
172
177
173
178
174
def _get_with_qiniu_mac (url , params , auth ):
179
175
qn_auth = qiniu .auth .QiniuMacRequestsAuth (
180
176
auth
181
177
) if auth is not None else None
182
- headers = __add_auth_headers ({}, auth )
183
178
184
- return _get (url , params , qn_auth , headers = headers )
179
+ return _get (url , params , qn_auth )
185
180
186
181
187
182
def _get_with_qiniu_mac_and_headers (url , params , auth , headers ):
@@ -229,76 +224,3 @@ def _delete_with_qiniu_mac_and_headers(url, params, auth, headers):
229
224
except Exception as e :
230
225
return None , ResponseInfo (None , e )
231
226
return __return_wrapper (r )
232
-
233
-
234
- class ResponseInfo (object ):
235
- """七牛HTTP请求返回信息类
236
-
237
- 该类主要是用于获取和解析对七牛发起各种请求后的响应包的header和body。
238
-
239
- Attributes:
240
- status_code: 整数变量,响应状态码
241
- text_body: 字符串变量,响应的body
242
- req_id: 字符串变量,七牛HTTP扩展字段,参考 https://developer.qiniu.com/kodo/3924/common-request-headers
243
- x_log: 字符串变量,七牛HTTP扩展字段,参考 https://developer.qiniu.com/kodo/3924/common-request-headers
244
- error: 字符串变量,响应的错误内容
245
- """
246
-
247
- def __init__ (self , response , exception = None ):
248
- """用响应包和异常信息初始化ResponseInfo类"""
249
- self .__response = response
250
- self .exception = exception
251
- if response is None :
252
- self .status_code = - 1
253
- self .text_body = None
254
- self .req_id = None
255
- self .x_log = None
256
- self .error = str (exception )
257
- else :
258
- self .status_code = response .status_code
259
- self .text_body = response .text
260
- self .req_id = response .headers .get ('X-Reqid' )
261
- self .x_log = response .headers .get ('X-Log' )
262
- if self .status_code >= 400 :
263
- if self .__check_json (response ):
264
- ret = response .json () if response .text != '' else None
265
- if ret is None :
266
- self .error = 'unknown'
267
- else :
268
- self .error = response .text
269
- else :
270
- self .error = response .text
271
- if self .req_id is None and self .status_code == 200 :
272
- self .error = 'server is not qiniu'
273
-
274
- def ok (self ):
275
- return self .status_code == 200 and self .req_id is not None
276
-
277
- def need_retry (self ):
278
- if self .__response is None or self .req_id is None :
279
- return True
280
- code = self .status_code
281
- if (code // 100 == 5 and code != 579 ) or code == 996 :
282
- return True
283
- return False
284
-
285
- def connect_failed (self ):
286
- return self .__response is None or self .req_id is None
287
-
288
- def __str__ (self ):
289
- if is_py2 :
290
- return ', ' .join (
291
- ['%s:%s' % item for item in self .__dict__ .items ()]).encode ('utf-8' )
292
- elif is_py3 :
293
- return ', ' .join (['%s:%s' %
294
- item for item in self .__dict__ .items ()])
295
-
296
- def __repr__ (self ):
297
- return self .__str__ ()
298
-
299
- def __check_json (self , reponse ):
300
- try :
301
- reponse .json ()
302
- return True
303
- except Exception :
304
- return False
0 commit comments