Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 49.02 KB | None | 0 0
  1. F
  2. backend_login_test.py:4 (test_login)
  3. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  4.  
  5. def _new_conn(self):
  6. """ Establish a socket connection and set nodelay settings on it.
  7.  
  8. :return: New socket connection.
  9. """
  10. extra_kw = {}
  11. if self.source_address:
  12. extra_kw['source_address'] = self.source_address
  13.  
  14. if self.socket_options:
  15. extra_kw['socket_options'] = self.socket_options
  16.  
  17. try:
  18. conn = connection.create_connection(
  19. > (self._dns_host, self.port), self.timeout, **extra_kw)
  20.  
  21. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/connection.py:171:
  22. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  23.  
  24. address = ('localhost', 80), timeout = None, source_address = None
  25. socket_options = [(6, 1, 1)]
  26.  
  27. def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  28. source_address=None, socket_options=None):
  29. """Connect to *address* and return the socket object.
  30.  
  31. Convenience function. Connect to *address* (a 2-tuple ``(host,
  32. port)``) and return the socket object. Passing the optional
  33. *timeout* parameter will set the timeout on the socket instance
  34. before attempting to connect. If no *timeout* is supplied, the
  35. global default timeout setting returned by :func:`getdefaulttimeout`
  36. is used. If *source_address* is set it must be a tuple of (host, port)
  37. for the socket to bind as a source address before making the connection.
  38. An host of '' or port 0 tells the OS to use the default.
  39. """
  40.  
  41. host, port = address
  42. if host.startswith('['):
  43. host = host.strip('[]')
  44. err = None
  45.  
  46. # Using the value from allowed_gai_family() in the context of getaddrinfo lets
  47. # us select whether to work with IPv4 DNS records, IPv6 records, or both.
  48. # The original create_connection function always returns all records.
  49. family = allowed_gai_family()
  50.  
  51. for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  52. af, socktype, proto, canonname, sa = res
  53. sock = None
  54. try:
  55. sock = socket.socket(af, socktype, proto)
  56.  
  57. # If provided, set socket level options before connecting.
  58. _set_socket_options(sock, socket_options)
  59.  
  60. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  61. sock.settimeout(timeout)
  62. if source_address:
  63. sock.bind(source_address)
  64. sock.connect(sa)
  65. return sock
  66.  
  67. except socket.error as e:
  68. err = e
  69. if sock is not None:
  70. sock.close()
  71. sock = None
  72.  
  73. if err is not None:
  74. > raise err
  75.  
  76. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/util/connection.py:79:
  77. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  78.  
  79. address = ('localhost', 80), timeout = None, source_address = None
  80. socket_options = [(6, 1, 1)]
  81.  
  82. def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  83. source_address=None, socket_options=None):
  84. """Connect to *address* and return the socket object.
  85.  
  86. Convenience function. Connect to *address* (a 2-tuple ``(host,
  87. port)``) and return the socket object. Passing the optional
  88. *timeout* parameter will set the timeout on the socket instance
  89. before attempting to connect. If no *timeout* is supplied, the
  90. global default timeout setting returned by :func:`getdefaulttimeout`
  91. is used. If *source_address* is set it must be a tuple of (host, port)
  92. for the socket to bind as a source address before making the connection.
  93. An host of '' or port 0 tells the OS to use the default.
  94. """
  95.  
  96. host, port = address
  97. if host.startswith('['):
  98. host = host.strip('[]')
  99. err = None
  100.  
  101. # Using the value from allowed_gai_family() in the context of getaddrinfo lets
  102. # us select whether to work with IPv4 DNS records, IPv6 records, or both.
  103. # The original create_connection function always returns all records.
  104. family = allowed_gai_family()
  105.  
  106. for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  107. af, socktype, proto, canonname, sa = res
  108. sock = None
  109. try:
  110. sock = socket.socket(af, socktype, proto)
  111.  
  112. # If provided, set socket level options before connecting.
  113. _set_socket_options(sock, socket_options)
  114.  
  115. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  116. sock.settimeout(timeout)
  117. if source_address:
  118. sock.bind(source_address)
  119. > sock.connect(sa)
  120. E ConnectionRefusedError: [Errno 111] Connection refused
  121.  
  122. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/util/connection.py:69: ConnectionRefusedError
  123.  
  124. During handling of the above exception, another exception occurred:
  125.  
  126. self = <urllib3.connectionpool.HTTPConnectionPool object at 0x7f30b283dba8>
  127. method = 'POST', url = '/api/auth'
  128. body = b'{"username": "test", "password": "test"}'
  129. headers = {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '40', 'Content-Type': 'application/json'}
  130. retries = Retry(total=0, connect=None, read=False, redirect=None, status=None)
  131. redirect = False, assert_same_host = False
  132. timeout = <urllib3.util.timeout.Timeout object at 0x7f30b283d5c0>
  133. pool_timeout = None, release_conn = False, chunked = False, body_pos = None
  134. response_kw = {'decode_content': False, 'preload_content': False}, conn = None
  135. release_this_conn = True, err = None, clean_exit = False
  136. timeout_obj = <urllib3.util.timeout.Timeout object at 0x7f30b282c400>
  137. is_new_proxy_conn = False
  138.  
  139. def urlopen(self, method, url, body=None, headers=None, retries=None,
  140. redirect=True, assert_same_host=True, timeout=_Default,
  141. pool_timeout=None, release_conn=None, chunked=False,
  142. body_pos=None, **response_kw):
  143. """
  144. Get a connection from the pool and perform an HTTP request. This is the
  145. lowest level call for making a request, so you'll need to specify all
  146. the raw details.
  147.  
  148. .. note::
  149.  
  150. More commonly, it's appropriate to use a convenience method provided
  151. by :class:`.RequestMethods`, such as :meth:`request`.
  152.  
  153. .. note::
  154.  
  155. `release_conn` will only behave as expected if
  156. `preload_content=False` because we want to make
  157. `preload_content=False` the default behaviour someday soon without
  158. breaking backwards compatibility.
  159.  
  160. :param method:
  161. HTTP request method (such as GET, POST, PUT, etc.)
  162.  
  163. :param body:
  164. Data to send in the request body (useful for creating
  165. POST requests, see HTTPConnectionPool.post_url for
  166. more convenience).
  167.  
  168. :param headers:
  169. Dictionary of custom headers to send, such as User-Agent,
  170. If-None-Match, etc. If None, pool headers are used. If provided,
  171. these headers completely replace any pool-specific headers.
  172.  
  173. :param retries:
  174. Configure the number of retries to allow before raising a
  175. :class:`~urllib3.exceptions.MaxRetryError` exception.
  176.  
  177. Pass ``None`` to retry until you receive a response. Pass a
  178. :class:`~urllib3.util.retry.Retry` object for fine-grained control
  179. over different types of retries.
  180. Pass an integer number to retry connection errors that many times,
  181. but no other types of errors. Pass zero to never retry.
  182.  
  183. If ``False``, then retries are disabled and any exception is raised
  184. immediately. Also, instead of raising a MaxRetryError on redirects,
  185. the redirect response will be returned.
  186.  
  187. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
  188.  
  189. :param redirect:
  190. If True, automatically handle redirects (status codes 301, 302,
  191. 303, 307, 308). Each redirect counts as a retry. Disabling retries
  192. will disable redirect, too.
  193.  
  194. :param assert_same_host:
  195. If ``True``, will make sure that the host of the pool requests is
  196. consistent else will raise HostChangedError. When False, you can
  197. use the pool on an HTTP proxy and request foreign hosts.
  198.  
  199. :param timeout:
  200. If specified, overrides the default timeout for this one
  201. request. It may be a float (in seconds) or an instance of
  202. :class:`urllib3.util.Timeout`.
  203.  
  204. :param pool_timeout:
  205. If set and the pool is set to block=True, then this method will
  206. block for ``pool_timeout`` seconds and raise EmptyPoolError if no
  207. connection is available within the time period.
  208.  
  209. :param release_conn:
  210. If False, then the urlopen call will not release the connection
  211. back into the pool once a response is received (but will release if
  212. you read the entire contents of the response such as when
  213. `preload_content=True`). This is useful if you're not preloading
  214. the response's content immediately. You will need to call
  215. ``r.release_conn()`` on the response ``r`` to return the connection
  216. back into the pool. If None, it takes the value of
  217. ``response_kw.get('preload_content', True)``.
  218.  
  219. :param chunked:
  220. If True, urllib3 will send the body using chunked transfer
  221. encoding. Otherwise, urllib3 will send the body using the standard
  222. content-length form. Defaults to False.
  223.  
  224. :param int body_pos:
  225. Position to seek to in file-like body in the event of a retry or
  226. redirect. Typically this won't need to be set because urllib3 will
  227. auto-populate the value when needed.
  228.  
  229. :param \\**response_kw:
  230. Additional parameters are passed to
  231. :meth:`urllib3.response.HTTPResponse.from_httplib`
  232. """
  233. if headers is None:
  234. headers = self.headers
  235.  
  236. if not isinstance(retries, Retry):
  237. retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
  238.  
  239. if release_conn is None:
  240. release_conn = response_kw.get('preload_content', True)
  241.  
  242. # Check host
  243. if assert_same_host and not self.is_same_host(url):
  244. raise HostChangedError(self, url, retries)
  245.  
  246. conn = None
  247.  
  248. # Track whether `conn` needs to be released before
  249. # returning/raising/recursing. Update this variable if necessary, and
  250. # leave `release_conn` constant throughout the function. That way, if
  251. # the function recurses, the original value of `release_conn` will be
  252. # passed down into the recursive call, and its value will be respected.
  253. #
  254. # See issue #651 [1] for details.
  255. #
  256. # [1] <https://github.com/shazow/urllib3/issues/651>
  257. release_this_conn = release_conn
  258.  
  259. # Merge the proxy headers. Only do this in HTTP. We have to copy the
  260. # headers dict so we can safely change it without those changes being
  261. # reflected in anyone else's copy.
  262. if self.scheme == 'http':
  263. headers = headers.copy()
  264. headers.update(self.proxy_headers)
  265.  
  266. # Must keep the exception bound to a separate variable or else Python 3
  267. # complains about UnboundLocalError.
  268. err = None
  269.  
  270. # Keep track of whether we cleanly exited the except block. This
  271. # ensures we do proper cleanup in finally.
  272. clean_exit = False
  273.  
  274. # Rewind body position, if needed. Record current position
  275. # for future rewinds in the event of a redirect/retry.
  276. body_pos = set_file_position(body, body_pos)
  277.  
  278. try:
  279. # Request a connection from the queue.
  280. timeout_obj = self._get_timeout(timeout)
  281. conn = self._get_conn(timeout=pool_timeout)
  282.  
  283. conn.timeout = timeout_obj.connect_timeout
  284.  
  285. is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None)
  286. if is_new_proxy_conn:
  287. self._prepare_proxy(conn)
  288.  
  289. # Make the request on the httplib connection object.
  290. httplib_response = self._make_request(conn, method, url,
  291. timeout=timeout_obj,
  292. body=body, headers=headers,
  293. > chunked=chunked)
  294.  
  295. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/connectionpool.py:600:
  296. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  297.  
  298. self = <urllib3.connectionpool.HTTPConnectionPool object at 0x7f30b283dba8>
  299. conn = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  300. method = 'POST', url = '/api/auth'
  301. timeout = <urllib3.util.timeout.Timeout object at 0x7f30b282c400>
  302. chunked = False
  303. httplib_request_kw = {'body': b'{"username": "test", "password": "test"}', 'headers': {'User-Agent': 'python-requests/2.19.1', 'Accept-Enco...ip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '40', 'Content-Type': 'application/json'}}
  304. timeout_obj = <urllib3.util.timeout.Timeout object at 0x7f30b2766518>
  305.  
  306. def _make_request(self, conn, method, url, timeout=_Default, chunked=False,
  307. **httplib_request_kw):
  308. """
  309. Perform a request on a given urllib connection object taken from our
  310. pool.
  311.  
  312. :param conn:
  313. a connection from one of our connection pools
  314.  
  315. :param timeout:
  316. Socket timeout in seconds for the request. This can be a
  317. float or integer, which will set the same timeout value for
  318. the socket connect and the socket read, or an instance of
  319. :class:`urllib3.util.Timeout`, which gives you more fine-grained
  320. control over your timeouts.
  321. """
  322. self.num_requests += 1
  323.  
  324. timeout_obj = self._get_timeout(timeout)
  325. timeout_obj.start_connect()
  326. conn.timeout = timeout_obj.connect_timeout
  327.  
  328. # Trigger any extra validation we need to do.
  329. try:
  330. self._validate_conn(conn)
  331. except (SocketTimeout, BaseSSLError) as e:
  332. # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
  333. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
  334. raise
  335.  
  336. # conn.request() calls httplib.*.request, not the method in
  337. # urllib3.request. It also calls makefile (recv) on the socket.
  338. if chunked:
  339. conn.request_chunked(method, url, **httplib_request_kw)
  340. else:
  341. > conn.request(method, url, **httplib_request_kw)
  342.  
  343. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/connectionpool.py:354:
  344. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  345.  
  346. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  347. method = 'POST', url = '/api/auth'
  348. body = b'{"username": "test", "password": "test"}'
  349. headers = {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '40', 'Content-Type': 'application/json'}
  350.  
  351. def request(self, method, url, body=None, headers={}, *,
  352. encode_chunked=False):
  353. """Send a complete request to the server."""
  354. > self._send_request(method, url, body, headers, encode_chunked)
  355.  
  356. /usr/lib/python3.6/http/client.py:1239:
  357. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  358.  
  359. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  360. method = 'POST', url = '/api/auth'
  361. body = b'{"username": "test", "password": "test"}'
  362. headers = {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '40', 'Content-Type': 'application/json'}
  363. encode_chunked = False
  364.  
  365. def _send_request(self, method, url, body, headers, encode_chunked):
  366. # Honor explicitly requested Host: and Accept-Encoding: headers.
  367. header_names = frozenset(k.lower() for k in headers)
  368. skips = {}
  369. if 'host' in header_names:
  370. skips['skip_host'] = 1
  371. if 'accept-encoding' in header_names:
  372. skips['skip_accept_encoding'] = 1
  373.  
  374. self.putrequest(method, url, **skips)
  375.  
  376. # chunked encoding will happen if HTTP/1.1 is used and either
  377. # the caller passes encode_chunked=True or the following
  378. # conditions hold:
  379. # 1. content-length has not been explicitly set
  380. # 2. the body is a file or iterable, but not a str or bytes-like
  381. # 3. Transfer-Encoding has NOT been explicitly set by the caller
  382.  
  383. if 'content-length' not in header_names:
  384. # only chunk body if not explicitly set for backwards
  385. # compatibility, assuming the client code is already handling the
  386. # chunking
  387. if 'transfer-encoding' not in header_names:
  388. # if content-length cannot be automatically determined, fall
  389. # back to chunked encoding
  390. encode_chunked = False
  391. content_length = self._get_content_length(body, method)
  392. if content_length is None:
  393. if body is not None:
  394. if self.debuglevel > 0:
  395. print('Unable to determine size of %r' % body)
  396. encode_chunked = True
  397. self.putheader('Transfer-Encoding', 'chunked')
  398. else:
  399. self.putheader('Content-Length', str(content_length))
  400. else:
  401. encode_chunked = False
  402.  
  403. for hdr, value in headers.items():
  404. self.putheader(hdr, value)
  405. if isinstance(body, str):
  406. # RFC 2616 Section 3.7.1 says that text default has a
  407. # default charset of iso-8859-1.
  408. body = _encode(body, 'body')
  409. > self.endheaders(body, encode_chunked=encode_chunked)
  410.  
  411. /usr/lib/python3.6/http/client.py:1285:
  412. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  413.  
  414. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  415. message_body = b'{"username": "test", "password": "test"}'
  416.  
  417. def endheaders(self, message_body=None, *, encode_chunked=False):
  418. """Indicate that the last header line has been sent to the server.
  419.  
  420. This method sends the request to the server. The optional message_body
  421. argument can be used to pass a message body associated with the
  422. request.
  423. """
  424. if self.__state == _CS_REQ_STARTED:
  425. self.__state = _CS_REQ_SENT
  426. else:
  427. raise CannotSendHeader()
  428. > self._send_output(message_body, encode_chunked=encode_chunked)
  429.  
  430. /usr/lib/python3.6/http/client.py:1234:
  431. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  432.  
  433. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  434. message_body = b'{"username": "test", "password": "test"}'
  435. encode_chunked = False
  436.  
  437. def _send_output(self, message_body=None, encode_chunked=False):
  438. """Send the currently buffered request and clear the buffer.
  439.  
  440. Appends an extra \\r\\n to the buffer.
  441. A message_body may be specified, to be appended to the request.
  442. """
  443. self._buffer.extend((b"", b""))
  444. msg = b"\r\n".join(self._buffer)
  445. del self._buffer[:]
  446. > self.send(msg)
  447.  
  448. /usr/lib/python3.6/http/client.py:1026:
  449. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  450.  
  451. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  452. data = b'POST /api/auth HTTP/1.1\r\nHost: localhost\r\nUser-Agent: python-requests/2.19.1\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\nContent-Length: 40\r\nContent-Type: application/json\r\n\r\n'
  453.  
  454. def send(self, data):
  455. """Send `data' to the server.
  456. ``data`` can be a string object, a bytes object, an array object, a
  457. file-like object that supports a .read() method, or an iterable object.
  458. """
  459.  
  460. if self.sock is None:
  461. if self.auto_open:
  462. > self.connect()
  463.  
  464. /usr/lib/python3.6/http/client.py:964:
  465. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  466.  
  467. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  468.  
  469. def connect(self):
  470. > conn = self._new_conn()
  471.  
  472. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/connection.py:196:
  473. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  474.  
  475. self = <urllib3.connection.HTTPConnection object at 0x7f30b282c898>
  476.  
  477. def _new_conn(self):
  478. """ Establish a socket connection and set nodelay settings on it.
  479.  
  480. :return: New socket connection.
  481. """
  482. extra_kw = {}
  483. if self.source_address:
  484. extra_kw['source_address'] = self.source_address
  485.  
  486. if self.socket_options:
  487. extra_kw['socket_options'] = self.socket_options
  488.  
  489. try:
  490. conn = connection.create_connection(
  491. (self._dns_host, self.port), self.timeout, **extra_kw)
  492.  
  493. except SocketTimeout as e:
  494. raise ConnectTimeoutError(
  495. self, "Connection to %s timed out. (connect timeout=%s)" %
  496. (self.host, self.timeout))
  497.  
  498. except SocketError as e:
  499. raise NewConnectionError(
  500. > self, "Failed to establish a new connection: %s" % e)
  501. E urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f30b282c898>: Failed to establish a new connection: [Errno 111] Connection refused
  502.  
  503. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/connection.py:180: NewConnectionError
  504.  
  505. During handling of the above exception, another exception occurred:
  506.  
  507. self = <requests.adapters.HTTPAdapter object at 0x7f30b283d6a0>
  508. request = <PreparedRequest [POST]>, stream = False
  509. timeout = <urllib3.util.timeout.Timeout object at 0x7f30b283d5c0>, verify = True
  510. cert = None, proxies = OrderedDict()
  511.  
  512. def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
  513. """Sends PreparedRequest object. Returns Response object.
  514.  
  515. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  516. :param stream: (optional) Whether to stream the request content.
  517. :param timeout: (optional) How long to wait for the server to send
  518. data before giving up, as a float, or a :ref:`(connect timeout,
  519. read timeout) <timeouts>` tuple.
  520. :type timeout: float or tuple or urllib3 Timeout object
  521. :param verify: (optional) Either a boolean, in which case it controls whether
  522. we verify the server's TLS certificate, or a string, in which case it
  523. must be a path to a CA bundle to use
  524. :param cert: (optional) Any user-provided SSL certificate to be trusted.
  525. :param proxies: (optional) The proxies dictionary to apply to the request.
  526. :rtype: requests.Response
  527. """
  528.  
  529. conn = self.get_connection(request.url, proxies)
  530.  
  531. self.cert_verify(conn, request.url, verify, cert)
  532. url = self.request_url(request, proxies)
  533. self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
  534.  
  535. chunked = not (request.body is None or 'Content-Length' in request.headers)
  536.  
  537. if isinstance(timeout, tuple):
  538. try:
  539. connect, read = timeout
  540. timeout = TimeoutSauce(connect=connect, read=read)
  541. except ValueError as e:
  542. # this may raise a string formatting error.
  543. err = ("Invalid timeout {0}. Pass a (connect, read) "
  544. "timeout tuple, or a single float to set "
  545. "both timeouts to the same value".format(timeout))
  546. raise ValueError(err)
  547. elif isinstance(timeout, TimeoutSauce):
  548. pass
  549. else:
  550. timeout = TimeoutSauce(connect=timeout, read=timeout)
  551.  
  552. try:
  553. if not chunked:
  554. resp = conn.urlopen(
  555. method=request.method,
  556. url=url,
  557. body=request.body,
  558. headers=request.headers,
  559. redirect=False,
  560. assert_same_host=False,
  561. preload_content=False,
  562. decode_content=False,
  563. retries=self.max_retries,
  564. > timeout=timeout
  565. )
  566.  
  567. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/requests/adapters.py:445:
  568. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  569.  
  570. self = <urllib3.connectionpool.HTTPConnectionPool object at 0x7f30b283dba8>
  571. method = 'POST', url = '/api/auth'
  572. body = b'{"username": "test", "password": "test"}'
  573. headers = {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '40', 'Content-Type': 'application/json'}
  574. retries = Retry(total=0, connect=None, read=False, redirect=None, status=None)
  575. redirect = False, assert_same_host = False
  576. timeout = <urllib3.util.timeout.Timeout object at 0x7f30b283d5c0>
  577. pool_timeout = None, release_conn = False, chunked = False, body_pos = None
  578. response_kw = {'decode_content': False, 'preload_content': False}, conn = None
  579. release_this_conn = True, err = None, clean_exit = False
  580. timeout_obj = <urllib3.util.timeout.Timeout object at 0x7f30b282c400>
  581. is_new_proxy_conn = False
  582.  
  583. def urlopen(self, method, url, body=None, headers=None, retries=None,
  584. redirect=True, assert_same_host=True, timeout=_Default,
  585. pool_timeout=None, release_conn=None, chunked=False,
  586. body_pos=None, **response_kw):
  587. """
  588. Get a connection from the pool and perform an HTTP request. This is the
  589. lowest level call for making a request, so you'll need to specify all
  590. the raw details.
  591.  
  592. .. note::
  593.  
  594. More commonly, it's appropriate to use a convenience method provided
  595. by :class:`.RequestMethods`, such as :meth:`request`.
  596.  
  597. .. note::
  598.  
  599. `release_conn` will only behave as expected if
  600. `preload_content=False` because we want to make
  601. `preload_content=False` the default behaviour someday soon without
  602. breaking backwards compatibility.
  603.  
  604. :param method:
  605. HTTP request method (such as GET, POST, PUT, etc.)
  606.  
  607. :param body:
  608. Data to send in the request body (useful for creating
  609. POST requests, see HTTPConnectionPool.post_url for
  610. more convenience).
  611.  
  612. :param headers:
  613. Dictionary of custom headers to send, such as User-Agent,
  614. If-None-Match, etc. If None, pool headers are used. If provided,
  615. these headers completely replace any pool-specific headers.
  616.  
  617. :param retries:
  618. Configure the number of retries to allow before raising a
  619. :class:`~urllib3.exceptions.MaxRetryError` exception.
  620.  
  621. Pass ``None`` to retry until you receive a response. Pass a
  622. :class:`~urllib3.util.retry.Retry` object for fine-grained control
  623. over different types of retries.
  624. Pass an integer number to retry connection errors that many times,
  625. but no other types of errors. Pass zero to never retry.
  626.  
  627. If ``False``, then retries are disabled and any exception is raised
  628. immediately. Also, instead of raising a MaxRetryError on redirects,
  629. the redirect response will be returned.
  630.  
  631. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
  632.  
  633. :param redirect:
  634. If True, automatically handle redirects (status codes 301, 302,
  635. 303, 307, 308). Each redirect counts as a retry. Disabling retries
  636. will disable redirect, too.
  637.  
  638. :param assert_same_host:
  639. If ``True``, will make sure that the host of the pool requests is
  640. consistent else will raise HostChangedError. When False, you can
  641. use the pool on an HTTP proxy and request foreign hosts.
  642.  
  643. :param timeout:
  644. If specified, overrides the default timeout for this one
  645. request. It may be a float (in seconds) or an instance of
  646. :class:`urllib3.util.Timeout`.
  647.  
  648. :param pool_timeout:
  649. If set and the pool is set to block=True, then this method will
  650. block for ``pool_timeout`` seconds and raise EmptyPoolError if no
  651. connection is available within the time period.
  652.  
  653. :param release_conn:
  654. If False, then the urlopen call will not release the connection
  655. back into the pool once a response is received (but will release if
  656. you read the entire contents of the response such as when
  657. `preload_content=True`). This is useful if you're not preloading
  658. the response's content immediately. You will need to call
  659. ``r.release_conn()`` on the response ``r`` to return the connection
  660. back into the pool. If None, it takes the value of
  661. ``response_kw.get('preload_content', True)``.
  662.  
  663. :param chunked:
  664. If True, urllib3 will send the body using chunked transfer
  665. encoding. Otherwise, urllib3 will send the body using the standard
  666. content-length form. Defaults to False.
  667.  
  668. :param int body_pos:
  669. Position to seek to in file-like body in the event of a retry or
  670. redirect. Typically this won't need to be set because urllib3 will
  671. auto-populate the value when needed.
  672.  
  673. :param \\**response_kw:
  674. Additional parameters are passed to
  675. :meth:`urllib3.response.HTTPResponse.from_httplib`
  676. """
  677. if headers is None:
  678. headers = self.headers
  679.  
  680. if not isinstance(retries, Retry):
  681. retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
  682.  
  683. if release_conn is None:
  684. release_conn = response_kw.get('preload_content', True)
  685.  
  686. # Check host
  687. if assert_same_host and not self.is_same_host(url):
  688. raise HostChangedError(self, url, retries)
  689.  
  690. conn = None
  691.  
  692. # Track whether `conn` needs to be released before
  693. # returning/raising/recursing. Update this variable if necessary, and
  694. # leave `release_conn` constant throughout the function. That way, if
  695. # the function recurses, the original value of `release_conn` will be
  696. # passed down into the recursive call, and its value will be respected.
  697. #
  698. # See issue #651 [1] for details.
  699. #
  700. # [1] <https://github.com/shazow/urllib3/issues/651>
  701. release_this_conn = release_conn
  702.  
  703. # Merge the proxy headers. Only do this in HTTP. We have to copy the
  704. # headers dict so we can safely change it without those changes being
  705. # reflected in anyone else's copy.
  706. if self.scheme == 'http':
  707. headers = headers.copy()
  708. headers.update(self.proxy_headers)
  709.  
  710. # Must keep the exception bound to a separate variable or else Python 3
  711. # complains about UnboundLocalError.
  712. err = None
  713.  
  714. # Keep track of whether we cleanly exited the except block. This
  715. # ensures we do proper cleanup in finally.
  716. clean_exit = False
  717.  
  718. # Rewind body position, if needed. Record current position
  719. # for future rewinds in the event of a redirect/retry.
  720. body_pos = set_file_position(body, body_pos)
  721.  
  722. try:
  723. # Request a connection from the queue.
  724. timeout_obj = self._get_timeout(timeout)
  725. conn = self._get_conn(timeout=pool_timeout)
  726.  
  727. conn.timeout = timeout_obj.connect_timeout
  728.  
  729. is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None)
  730. if is_new_proxy_conn:
  731. self._prepare_proxy(conn)
  732.  
  733. # Make the request on the httplib connection object.
  734. httplib_response = self._make_request(conn, method, url,
  735. timeout=timeout_obj,
  736. body=body, headers=headers,
  737. chunked=chunked)
  738.  
  739. # If we're going to release the connection in ``finally:``, then
  740. # the response doesn't need to know about the connection. Otherwise
  741. # it will also try to release it and we'll have a double-release
  742. # mess.
  743. response_conn = conn if not release_conn else None
  744.  
  745. # Pass method to Response for length checking
  746. response_kw['request_method'] = method
  747.  
  748. # Import httplib's response into our own wrapper object
  749. response = self.ResponseCls.from_httplib(httplib_response,
  750. pool=self,
  751. connection=response_conn,
  752. retries=retries,
  753. **response_kw)
  754.  
  755. # Everything went great!
  756. clean_exit = True
  757.  
  758. except queue.Empty:
  759. # Timed out by queue.
  760. raise EmptyPoolError(self, "No pool connections are available.")
  761.  
  762. except (TimeoutError, HTTPException, SocketError, ProtocolError,
  763. BaseSSLError, SSLError, CertificateError) as e:
  764. # Discard the connection for these exceptions. It will be
  765. # replaced during the next _get_conn() call.
  766. clean_exit = False
  767. if isinstance(e, (BaseSSLError, CertificateError)):
  768. e = SSLError(e)
  769. elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:
  770. e = ProxyError('Cannot connect to proxy.', e)
  771. elif isinstance(e, (SocketError, HTTPException)):
  772. e = ProtocolError('Connection aborted.', e)
  773.  
  774. retries = retries.increment(method, url, error=e, _pool=self,
  775. > _stacktrace=sys.exc_info()[2])
  776.  
  777. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/connectionpool.py:638:
  778. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  779.  
  780. self = Retry(total=0, connect=None, read=False, redirect=None, status=None)
  781. method = 'POST', url = '/api/auth', response = None
  782. error = NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f30b282c898>: Failed to establish a new connection: [Errno 111] Connection refused',)
  783. _pool = <urllib3.connectionpool.HTTPConnectionPool object at 0x7f30b283dba8>
  784. _stacktrace = <traceback object at 0x7f30b29368c8>
  785.  
  786. def increment(self, method=None, url=None, response=None, error=None,
  787. _pool=None, _stacktrace=None):
  788. """ Return a new Retry object with incremented retry counters.
  789.  
  790. :param response: A response object, or None, if the server did not
  791. return a response.
  792. :type response: :class:`~urllib3.response.HTTPResponse`
  793. :param Exception error: An error encountered during the request, or
  794. None if the response was received successfully.
  795.  
  796. :return: A new ``Retry`` object.
  797. """
  798. if self.total is False and error:
  799. # Disabled, indicate to re-raise the error.
  800. raise six.reraise(type(error), error, _stacktrace)
  801.  
  802. total = self.total
  803. if total is not None:
  804. total -= 1
  805.  
  806. connect = self.connect
  807. read = self.read
  808. redirect = self.redirect
  809. status_count = self.status
  810. cause = 'unknown'
  811. status = None
  812. redirect_location = None
  813.  
  814. if error and self._is_connection_error(error):
  815. # Connect retry?
  816. if connect is False:
  817. raise six.reraise(type(error), error, _stacktrace)
  818. elif connect is not None:
  819. connect -= 1
  820.  
  821. elif error and self._is_read_error(error):
  822. # Read retry?
  823. if read is False or not self._is_method_retryable(method):
  824. raise six.reraise(type(error), error, _stacktrace)
  825. elif read is not None:
  826. read -= 1
  827.  
  828. elif response and response.get_redirect_location():
  829. # Redirect retry?
  830. if redirect is not None:
  831. redirect -= 1
  832. cause = 'too many redirects'
  833. redirect_location = response.get_redirect_location()
  834. status = response.status
  835.  
  836. else:
  837. # Incrementing because of a server error like a 500 in
  838. # status_forcelist and a the given method is in the whitelist
  839. cause = ResponseError.GENERIC_ERROR
  840. if response and response.status:
  841. if status_count is not None:
  842. status_count -= 1
  843. cause = ResponseError.SPECIFIC_ERROR.format(
  844. status_code=response.status)
  845. status = response.status
  846.  
  847. history = self.history + (RequestHistory(method, url, error, status, redirect_location),)
  848.  
  849. new_retry = self.new(
  850. total=total,
  851. connect=connect, read=read, redirect=redirect, status=status_count,
  852. history=history)
  853.  
  854. if new_retry.is_exhausted():
  855. > raise MaxRetryError(_pool, url, error or ResponseError(cause))
  856. E urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=80): Max retries exceeded with url: /api/auth (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f30b282c898>: Failed to establish a new connection: [Errno 111] Connection refused',))
  857.  
  858. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/urllib3/util/retry.py:398: MaxRetryError
  859.  
  860. During handling of the above exception, another exception occurred:
  861.  
  862. app = <Flask 'cc'>, client = <FlaskClient <Flask 'cc'>>
  863.  
  864. def test_login(app, client):
  865. _create_dummy_user(app, client)
  866. > resp = client.post('/login', data={"username": "test", "password": "test"})
  867.  
  868. backend_login_test.py:7:
  869. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  870. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/werkzeug/test.py:840: in post
  871. return self.open(*args, **kw)
  872. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/testing.py:200: in open
  873. follow_redirects=follow_redirects
  874. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/werkzeug/test.py:803: in open
  875. response = self.run_wsgi_app(environ, buffered=buffered)
  876. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/werkzeug/test.py:716: in run_wsgi_app
  877. rv = run_wsgi_app(self.application, environ, buffered=buffered)
  878. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/werkzeug/test.py:923: in run_wsgi_app
  879. app_rv = app(environ, start_response)
  880. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:2309: in __call__
  881. return self.wsgi_app(environ, start_response)
  882. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:2295: in wsgi_app
  883. response = self.handle_exception(e)
  884. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:1741: in handle_exception
  885. reraise(exc_type, exc_value, tb)
  886. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/_compat.py:35: in reraise
  887. raise value
  888. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:2292: in wsgi_app
  889. response = self.full_dispatch_request()
  890. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:1815: in full_dispatch_request
  891. rv = self.handle_user_exception(e)
  892. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:1718: in handle_user_exception
  893. reraise(exc_type, exc_value, tb)
  894. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/_compat.py:35: in reraise
  895. raise value
  896. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:1813: in full_dispatch_request
  897. rv = self.dispatch_request()
  898. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/flask/app.py:1799: in dispatch_request
  899. return self.view_functions[rule.endpoint](**req.view_args)
  900. ../cc/views/utils.py:26: in wrapper
  901. return view_func(*args, **kwargs)
  902. ../cc/views/general.py:22: in login
  903. json={'username': username, 'password': password}).json().get('token')
  904. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/requests/api.py:112: in post
  905. return request('post', url, data=data, json=json, **kwargs)
  906. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/requests/api.py:58: in request
  907. return session.request(method=method, url=url, **kwargs)
  908. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/requests/sessions.py:512: in request
  909. resp = self.send(prep, **send_kwargs)
  910. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/requests/sessions.py:622: in send
  911. r = adapter.send(request, **kwargs)
  912. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  913.  
  914. self = <requests.adapters.HTTPAdapter object at 0x7f30b283d6a0>
  915. request = <PreparedRequest [POST]>, stream = False
  916. timeout = <urllib3.util.timeout.Timeout object at 0x7f30b283d5c0>, verify = True
  917. cert = None, proxies = OrderedDict()
  918.  
  919. def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
  920. """Sends PreparedRequest object. Returns Response object.
  921.  
  922. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  923. :param stream: (optional) Whether to stream the request content.
  924. :param timeout: (optional) How long to wait for the server to send
  925. data before giving up, as a float, or a :ref:`(connect timeout,
  926. read timeout) <timeouts>` tuple.
  927. :type timeout: float or tuple or urllib3 Timeout object
  928. :param verify: (optional) Either a boolean, in which case it controls whether
  929. we verify the server's TLS certificate, or a string, in which case it
  930. must be a path to a CA bundle to use
  931. :param cert: (optional) Any user-provided SSL certificate to be trusted.
  932. :param proxies: (optional) The proxies dictionary to apply to the request.
  933. :rtype: requests.Response
  934. """
  935.  
  936. conn = self.get_connection(request.url, proxies)
  937.  
  938. self.cert_verify(conn, request.url, verify, cert)
  939. url = self.request_url(request, proxies)
  940. self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
  941.  
  942. chunked = not (request.body is None or 'Content-Length' in request.headers)
  943.  
  944. if isinstance(timeout, tuple):
  945. try:
  946. connect, read = timeout
  947. timeout = TimeoutSauce(connect=connect, read=read)
  948. except ValueError as e:
  949. # this may raise a string formatting error.
  950. err = ("Invalid timeout {0}. Pass a (connect, read) "
  951. "timeout tuple, or a single float to set "
  952. "both timeouts to the same value".format(timeout))
  953. raise ValueError(err)
  954. elif isinstance(timeout, TimeoutSauce):
  955. pass
  956. else:
  957. timeout = TimeoutSauce(connect=timeout, read=timeout)
  958.  
  959. try:
  960. if not chunked:
  961. resp = conn.urlopen(
  962. method=request.method,
  963. url=url,
  964. body=request.body,
  965. headers=request.headers,
  966. redirect=False,
  967. assert_same_host=False,
  968. preload_content=False,
  969. decode_content=False,
  970. retries=self.max_retries,
  971. timeout=timeout
  972. )
  973.  
  974. # Send the request.
  975. else:
  976. if hasattr(conn, 'proxy_pool'):
  977. conn = conn.proxy_pool
  978.  
  979. low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)
  980.  
  981. try:
  982. low_conn.putrequest(request.method,
  983. url,
  984. skip_accept_encoding=True)
  985.  
  986. for header, value in request.headers.items():
  987. low_conn.putheader(header, value)
  988.  
  989. low_conn.endheaders()
  990.  
  991. for i in request.body:
  992. low_conn.send(hex(len(i))[2:].encode('utf-8'))
  993. low_conn.send(b'\r\n')
  994. low_conn.send(i)
  995. low_conn.send(b'\r\n')
  996. low_conn.send(b'0\r\n\r\n')
  997.  
  998. # Receive the response from the server
  999. try:
  1000. # For Python 2.7+ versions, use buffering of HTTP
  1001. # responses
  1002. r = low_conn.getresponse(buffering=True)
  1003. except TypeError:
  1004. # For compatibility with Python 2.6 versions and back
  1005. r = low_conn.getresponse()
  1006.  
  1007. resp = HTTPResponse.from_httplib(
  1008. r,
  1009. pool=conn,
  1010. connection=low_conn,
  1011. preload_content=False,
  1012. decode_content=False
  1013. )
  1014. except:
  1015. # If we hit any problems here, clean up the connection.
  1016. # Then, reraise so that we can handle the actual exception.
  1017. low_conn.close()
  1018. raise
  1019.  
  1020. except (ProtocolError, socket.error) as err:
  1021. raise ConnectionError(err, request=request)
  1022.  
  1023. except MaxRetryError as e:
  1024. if isinstance(e.reason, ConnectTimeoutError):
  1025. # TODO: Remove this in 3.0.0: see #2811
  1026. if not isinstance(e.reason, NewConnectionError):
  1027. raise ConnectTimeout(e, request=request)
  1028.  
  1029. if isinstance(e.reason, ResponseError):
  1030. raise RetryError(e, request=request)
  1031.  
  1032. if isinstance(e.reason, _ProxyError):
  1033. raise ProxyError(e, request=request)
  1034.  
  1035. if isinstance(e.reason, _SSLError):
  1036. # This branch is for urllib3 v1.22 and later.
  1037. raise SSLError(e, request=request)
  1038.  
  1039. > raise ConnectionError(e, request=request)
  1040. E requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=80): Max retries exceeded with url: /api/auth (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f30b282c898>: Failed to establish a new connection: [Errno 111] Connection refused',))
  1041.  
  1042. ../../../.virtualenvs/CC-ar9V6dQt/lib/python3.6/site-packages/requests/adapters.py:513: ConnectionError
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement