Недавно я столкнулся с проблемой при попытке подключиться к API Salesforce с помощью Python simple-salesforce и запрашивает библиотеку для загрузки некоторых данных для некоторых приложений PowerBI и аналитики/приложений прогнозирования/машинного обучения.
Я использую Python 3.10.4 в Windows 10, и у меня установлена последняя опубликованная версия запросов и простых продаж.
Я получаю сообщение об ошибке SSL. не удалось пройти самоаттестацию. Меня сбивает с толку то, что у меня есть еще один конвейер в golang, который отлично работает на той же машине. Мне удалось реализовать обходной путь, установив параметрverify=False в сеансе и передав его в запросы. Я также могу получить ответ от сервера, используя urllib3 нижнего уровня для выполнения того же запроса, который работает нормально.
---------------------------------------------------------------------------
SSLCertVerificationError Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py:466, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
465 try:
--> 466 self._validate_conn(conn)
467 except (SocketTimeout, BaseSSLError) as e:
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py:1095, in HTTPSConnectionPool._validate_conn(self, conn)
1094 if conn.is_closed:
-> 1095 conn.connect()
1097 # TODO revise this, see https://github.com/urllib3/urllib3/issues/2791
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py:730, in HTTPSConnection.connect(self)
728 server_hostname_rm_dot = server_hostname.rstrip(".")
--> 730 sock_and_verified = _ssl_wrap_socket_and_match_hostname(
731 sock=sock,
732 cert_reqs=self.cert_reqs,
733 ssl_version=self.ssl_version,
734 ssl_minimum_version=self.ssl_minimum_version,
735 ssl_maximum_version=self.ssl_maximum_version,
736 ca_certs=self.ca_certs,
737 ca_cert_dir=self.ca_cert_dir,
738 ca_cert_data=self.ca_cert_data,
739 cert_file=self.cert_file,
740 key_file=self.key_file,
741 key_password=self.key_password,
742 server_hostname=server_hostname_rm_dot,
743 ssl_context=self.ssl_context,
744 tls_in_tls=tls_in_tls,
745 assert_hostname=self.assert_hostname,
746 assert_fingerprint=self.assert_fingerprint,
747 )
748 self.sock = sock_and_verified.socket
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py:909, in _ssl_wrap_socket_and_match_hostname(sock, cert_reqs, ssl_version, ssl_minimum_version, ssl_maximum_version, cert_file, key_file, key_password, ca_certs, ca_cert_dir, ca_cert_data, assert_hostname, assert_fingerprint, server_hostname, ssl_context, tls_in_tls)
907 server_hostname = normalized
--> 909 ssl_sock = ssl_wrap_socket(
910 sock=sock,
911 keyfile=key_file,
912 certfile=cert_file,
913 key_password=key_password,
914 ca_certs=ca_certs,
915 ca_cert_dir=ca_cert_dir,
916 ca_cert_data=ca_cert_data,
917 server_hostname=server_hostname,
918 ssl_context=context,
919 tls_in_tls=tls_in_tls,
920 )
922 try:
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\ssl_.py:469, in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir, key_password, ca_cert_data, tls_in_tls)
467 context.set_alpn_protocols(ALPN_PROTOCOLS)
--> 469 ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)
470 return ssl_sock
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\ssl_.py:513, in _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname)
511 return SSLTransport(sock, ssl_context, server_hostname)
--> 513 return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
File ~\AppData\Local\Programs\Python\Python310\lib\ssl.py:512, in SSLContext.wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
506 def wrap_socket(self, sock, server_side=False,
507 do_handshake_on_connect=True,
508 suppress_ragged_eofs=True,
509 server_hostname=None, session=None):
510 # SSLSocket class handles server_hostname encoding before it calls
511 # ctx._wrap_socket()
--> 512 return self.sslsocket_class._create(
513 sock=sock,
514 server_side=server_side,
515 do_handshake_on_connect=do_handshake_on_connect,
516 suppress_ragged_eofs=suppress_ragged_eofs,
517 server_hostname=server_hostname,
518 context=self,
519 session=session
520 )
File ~\AppData\Local\Programs\Python\Python310\lib\ssl.py:1070, in SSLSocket._create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session)
1069 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
-> 1070 self.do_handshake()
1071 except (OSError, ValueError):
File ~\AppData\Local\Programs\Python\Python310\lib\ssl.py:1341, in SSLSocket.do_handshake(self, block)
1340 self.settimeout(None)
-> 1341 self._sslobj.do_handshake()
1342 finally:
SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)
During handling of the above exception, another exception occurred:
SSLError Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py:789, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
788 # Make the request on the HTTPConnection object
--> 789 response = self._make_request(
790 conn,
791 method,
792 url,
793 timeout=timeout_obj,
794 body=body,
795 headers=headers,
796 chunked=chunked,
797 retries=retries,
798 response_conn=response_conn,
799 preload_content=preload_content,
800 decode_content=decode_content,
801 **response_kw,
802 )
804 # Everything went great!
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py:490, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
489 new_e = _wrap_proxy_error(new_e, conn.proxy.scheme)
--> 490 raise new_e
492 # conn.request() calls http.client.*.request, not the method in
493 # urllib3.request. It also calls makefile (recv) on the socket.
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)
The above exception was the direct cause of the following exception:
MaxRetryError Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py:667, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
666 try:
--> 667 resp = conn.urlopen(
668 method=request.method,
669 url=url,
670 body=request.body,
671 headers=request.headers,
672 redirect=False,
673 assert_same_host=False,
674 preload_content=False,
675 decode_content=False,
676 retries=self.max_retries,
677 timeout=timeout,
678 chunked=chunked,
679 )
681 except (ProtocolError, OSError) as err:
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py:843, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
841 new_e = ProtocolError("Connection aborted.", new_e)
--> 843 retries = retries.increment(
844 method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
845 )
846 retries.sleep()
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\retry.py:519, in Retry.increment(self, method, url, response, error, _pool, _stacktrace)
518 reason = error or ResponseError(cause)
--> 519 raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
521 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
MaxRetryError: HTTPSConnectionPool(host='login.salesforce.com', port=443): Max retries exceeded with url: /services/Soap/u/59.0 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)')))
During handling of the above exception, another exception occurred:
SSLError Traceback (most recent call last)
Input In [57], in ()
1 s.verify = requests.certs.where()
2 s.headers = headers
----> 3 resp = s.post(url)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py:637, in Session.post(self, url, data, json, **kwargs)
626 def post(self, url, data=None, json=None, **kwargs):
627 r"""Sends a POST request. Returns :class:`Response` object.
628
629 :param url: URL for the new :class:`Request` object.
(...)
634 :rtype: requests.Response
635 """
--> 637 return self.request("POST", url, data=data, json=json, **kwargs)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py:589, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
584 send_kwargs = {
585 "timeout": timeout,
586 "allow_redirects": allow_redirects,
587 }
588 send_kwargs.update(settings)
--> 589 resp = self.send(prep, **send_kwargs)
591 return resp
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py:703, in Session.send(self, request, **kwargs)
700 start = preferred_clock()
702 # Send the request
--> 703 r = adapter.send(request, **kwargs)
705 # Total elapsed time of the request (approximately)
706 elapsed = preferred_clock() - start
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py:698, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
694 raise ProxyError(e, request=request)
696 if isinstance(e.reason, _SSLError):
697 # This branch is for urllib3 v1.22 and later.
--> 698 raise SSLError(e, request=request)
700 raise ConnectionError(e, request=request)
702 except ClosedPoolError as e:
SSLError: HTTPSConnectionPool(host='login.salesforce.com', port=443): Max retries exceeded with url: /services/Soap/u/59.0 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)')))
Я также подключился по SSH к отдельной машине и смог успешно подключиться. Я не уверен, каковы мои дальнейшие действия. Хотя мой долгосрочный план состоит в том, чтобы перенести большую часть извлечений на golang, поскольку распространение проще, с Python намного проще работать на исследовательском этапе, особенно когда я хочу запускать что-то локально, а не на удаленном сервере.
Недавно я столкнулся с проблемой при попытке подключиться к API Salesforce с помощью Python simple-salesforce и запрашивает библиотеку для загрузки некоторых данных для некоторых приложений PowerBI и аналитики/приложений прогнозирования/машинного обучения. Я использую Python 3.10.4 в Windows 10, и у меня установлена последняя опубликованная версия запросов и простых продаж. Я получаю сообщение об ошибке SSL. не удалось пройти самоаттестацию. Меня сбивает с толку то, что у меня есть еще один конвейер в golang, который отлично работает на той же машине. Мне удалось реализовать обходной путь, установив параметрverify=False в сеансе и передав его в запросы. Я также могу получить ответ от сервера, используя urllib3 нижнего уровня для выполнения того же запроса, который работает нормально. [code]--------------------------------------------------------------------------- SSLCertVerificationError Traceback (most recent call last) File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py:466, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length) 465 try: --> 466 self._validate_conn(conn) 467 except (SocketTimeout, BaseSSLError) as e:
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py:1095, in HTTPSConnectionPool._validate_conn(self, conn) 1094 if conn.is_closed: -> 1095 conn.connect() 1097 # TODO revise this, see https://github.com/urllib3/urllib3/issues/2791
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\retry.py:519, in Retry.increment(self, method, url, response, error, _pool, _stacktrace) 518 reason = error or ResponseError(cause) --> 519 raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type] 521 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
MaxRetryError: HTTPSConnectionPool(host='login.salesforce.com', port=443): Max retries exceeded with url: /services/Soap/u/59.0 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)')))
During handling of the above exception, another exception occurred:
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py:703, in Session.send(self, request, **kwargs) 700 start = preferred_clock() 702 # Send the request --> 703 r = adapter.send(request, **kwargs) 705 # Total elapsed time of the request (approximately) 706 elapsed = preferred_clock() - start
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py:698, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies) 694 raise ProxyError(e, request=request) 696 if isinstance(e.reason, _SSLError): 697 # This branch is for urllib3 v1.22 and later. --> 698 raise SSLError(e, request=request) 700 raise ConnectionError(e, request=request) 702 except ClosedPoolError as e:
SSLError: HTTPSConnectionPool(host='login.salesforce.com', port=443): Max retries exceeded with url: /services/Soap/u/59.0 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)'))) [/code] Я также подключился по SSH к отдельной машине и смог успешно подключиться. Я не уверен, каковы мои дальнейшие действия. Хотя мой долгосрочный план состоит в том, чтобы перенести большую часть извлечений на golang, поскольку распространение проще, с Python намного проще работать на исследовательском этапе, особенно когда я хочу запускать что-то локально, а не на удаленном сервере.