当我尝试通过 Jupyter 连接到 Snowflake 时,snowflake.connector.connect() 出现异常

问题描述 投票:0回答:1

使用在Python 3.9.7上运行的Jupyter,我无法使用snowflake.connector.connect创建与snowflake的连接。该单元将运行约 2 分钟并抛出错误,提示

MethodNotAllowed: 000405: HTTP 405: Method not allowed

我在网上看到可能是我的python路径没有设置。我可以看到 Snowflake.connector 安装在

'C:\Users\{user}\AppData\Roaming\Python\Python39\site-packages\snowflake\connector' 
我有两个 PATH 变量是:

C:\Users\{user}\AppData\Local\Programs\Python\Launcher\
%USERPROFILE%\AppData\Local\Microsoft\WindowsApps

以上两个路径指向我之前安装的Python 3.11,但无法在VSCode中使用Jupyter连接,所以我保留了3.9版本。虽然我安装的其他可以工作的软件包也位于

C:\Users\{user}\AppData\Roaming\Python\Python39\site-packages\
中,但它不是我的 PATH 变量之一。

整天四处寻找以解决此问题,但无法解决。我收到的错误如下,了解更多信息。

我是设置 Python 环境的初学者,因此欢迎您提供任何进一步的建议。谢谢

RetryRequest                              Traceback (most recent call last)
File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\network.py:857, in SnowflakeRestful._request_exec_wrapper(self, session, method, full_url, headers, data, retry_ctx, no_retry, token, **kwargs)
    856 try:
--> 857     return_object = self._request_exec(
    858         session=session,
    859         method=method,
    860         full_url=full_url,
    861         headers=headers,
    862         data=data,
    863         token=token,
    864         **kwargs,
    865     )
    866     if return_object is not None:

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\network.py:1131, in SnowflakeRestful._request_exec(self, session, method, full_url, headers, data, token, catch_okta_unauthorized_error, is_raw_text, is_raw_binary, binary_data_handler, socket_timeout)
   1122 TelemetryService.get_instance().log_http_request_error(
   1123     "HttpException%s" % str(err),
   1124     full_url,
   (...)
   1129     stack_trace=traceback.format_exc(),
   1130 )
-> 1131 raise err

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\network.py:1062, in SnowflakeRestful._request_exec(self, session, method, full_url, headers, data, token, catch_okta_unauthorized_error, is_raw_text, is_raw_binary, binary_data_handler, socket_timeout)
   1061     # retryable server exceptions
-> 1062     raise RetryRequest(error)
   1064 elif (
   1065     raw_ret.status_code == UNAUTHORIZED
   1066     and catch_okta_unauthorized_error
   1067 ):
   1068     # OKTA Unauthorized errors

RetryRequest: 000405: HTTP 405: Method not allowed

During handling of the above exception, another exception occurred:

MethodNotAllowed                          Traceback (most recent call last)
Cell In[3], line 1
----> 1 snow = connector.connect(
      2     account='[accountname]',
      3     authenticator='externalbrowser',
      4     user='[user]',
      5     role='[role]',
      6     database='[db]',
      7     schema='[sch]',
      8     warehouse='[wrh]'
      9     )

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\__init__.py:51, in Connect(**kwargs)
     50 def Connect(**kwargs) -> SnowflakeConnection:
---> 51     return SnowflakeConnection(**kwargs)

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\connection.py:304, in SnowflakeConnection.__init__(self, **kwargs)
    302 self.converter = None
    303 self.__set_error_attributes()
--> 304 self.connect(**kwargs)
    305 self._telemetry = TelemetryClient(self._rest)
    307 # get the imported modules from sys.modules

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\connection.py:571, in SnowflakeConnection.connect(self, **kwargs)
    569         connection_diag.generate_report()
    570 else:
--> 571     self.__open_connection()

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\connection.py:839, in SnowflakeConnection.__open_connection(self)
    835 else:
    836     # okta URL, e.g., https://<account>.okta.com/
    837     self.auth_class = AuthByOkta(application=self.application)
--> 839 self.authenticate_with_retry(self.auth_class)
    841 self._password = None  # ensure password won't persist
    842 self.auth_class.reset_secrets()

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\connection.py:1099, in SnowflakeConnection.authenticate_with_retry(self, auth_instance)
   1096 def authenticate_with_retry(self, auth_instance) -> None:
   1097     # make some changes if needed before real __authenticate
   1098     try:
-> 1099         self._authenticate(auth_instance)
   1100     except ReauthenticationRequest as ex:
   1101         # cached id_token expiration error, we have cleaned id_token and try to authenticate again
   1102         logger.debug("ID token expired. Reauthenticating...: %s", ex)

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\connection.py:1111, in SnowflakeConnection._authenticate(self, auth_instance)
   1110 def _authenticate(self, auth_instance: AuthByPlugin):
-> 1111     auth_instance.prepare(
   1112         conn=self,
   1113         authenticator=self._authenticator,
   1114         service_name=self.service_name,
   1115         account=self.account,
   1116         user=self.user,
   1117         password=self._password,
   1118     )
   1119     self._consent_cache_id_token = getattr(
   1120         auth_instance, "consent_cache_id_token", True
   1121     )
   1123     auth = Auth(self.rest)

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\auth\webbrowser.py:137, in AuthByWebBrowser.prepare(self, conn, authenticator, service_name, account, user, **kwargs)
    134 callback_port = socket_connection.getsockname()[1]
    136 logger.debug("step 1: query GS to obtain SSO url")
--> 137 sso_url = self._get_sso_url(
    138     conn, authenticator, service_name, account, callback_port, user
    139 )
    141 logger.debug("Validate SSO URL")
    142 if not is_valid_url(sso_url):

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\auth\webbrowser.py:404, in AuthByWebBrowser._get_sso_url(self, conn, authenticator, service_name, account, callback_port, user)
    400 body["data"]["BROWSER_MODE_REDIRECT_PORT"] = str(callback_port)
    401 logger.debug(
    402     "account=%s, authenticator=%s, user=%s", account, authenticator, user
    403 )
--> 404 ret = conn._rest._post_request(
    405     url,
    406     headers,
    407     json.dumps(body),
    408     timeout=conn._rest._connection.login_timeout,
    409     socket_timeout=conn._rest._connection.login_timeout,
    410 )
    411 if not ret["success"]:
    412     self._handle_failure(conn=conn, ret=ret)

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\network.py:716, in SnowflakeRestful._post_request(self, url, headers, body, token, timeout, _no_results, no_retry, socket_timeout, _include_retry_params)
    713     ret = probe_connection(full_url)
    714     pprint(ret)
--> 716 ret = self.fetch(
    717     "post",
    718     full_url,
    719     headers,
    720     data=body,
    721     timeout=timeout,
    722     token=token,
    723     no_retry=no_retry,
    724     socket_timeout=socket_timeout,
    725     _include_retry_params=_include_retry_params,
    726 )
    727 logger.debug(
    728     "ret[code] = {code}, after post request".format(
    729         code=(ret.get("code", "N/A"))
    730     )
    731 )
    733 if ret.get("code") == SESSION_EXPIRED_GS_CODE:

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\network.py:814, in SnowflakeRestful.fetch(self, method, full_url, headers, data, timeout, **kwargs)
    812 retry_ctx = RetryCtx(timeout, include_retry_params)
    813 while True:
--> 814     ret = self._request_exec_wrapper(
    815         session, method, full_url, headers, data, retry_ctx, **kwargs
    816     )
    817     if ret is not None:
    818         return ret

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\network.py:910, in SnowflakeRestful._request_exec_wrapper(self, session, method, full_url, headers, data, retry_ctx, no_retry, token, **kwargs)
    908     retry_ctx.timeout -= int(time.time() - start_request_thread)
    909     if retry_ctx.timeout <= 0:
--> 910         self.log_and_handle_http_error_with_cause(
    911             e,
    912             full_url,
    913             method,
    914             retry_ctx.total_timeout,
    915             retry_ctx.cnt,
    916             conn,
    917         )
    918         return {}  # required for tests
    919 sleeping_time = retry_ctx.next_sleep()

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\network.py:965, in SnowflakeRestful.log_and_handle_http_error_with_cause(self, e, full_url, method, retry_timeout, retry_count, conn, timed_out)
    953 TelemetryService.get_instance().log_http_request_error(
    954     "HttpRequestRetryTimeout" if timed_out else f"HttpRequestError: {cause}",
    955     full_url,
   (...)
    962     stack_trace=traceback.format_exc(),
    963 )
    964 if isinstance(cause, Error):
--> 965     Error.errorhandler_wrapper_from_cause(conn, cause)
    966 else:
    967     self.handle_invalid_certificate_error(conn, full_url, cause)

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\errors.py:255, in Error.errorhandler_wrapper_from_cause(connection, cause, cursor)
    234 @staticmethod
    235 def errorhandler_wrapper_from_cause(
    236     connection: SnowflakeConnection,
    237     cause: Error | Exception,
    238     cursor: SnowflakeCursor | None = None,
    239 ) -> None:
    240     """Wrapper for errorhandler_wrapper, it is called with a cause instead of a dictionary.
    241 
    242     The dictionary is first extracted from the cause and then it's given to errorhandler_wrapper
   (...)
    253         A Snowflake error if connection and cursor are None.
    254     """
--> 255     return Error.errorhandler_wrapper(
    256         connection,
    257         cursor,
    258         type(cause),
    259         {
    260             "msg": cause.msg,
    261             "errno": cause.errno,
    262             "sqlstate": cause.sqlstate,
    263             "done_format_msg": True,
    264         },
    265     )

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\errors.py:290, in Error.errorhandler_wrapper(connection, cursor, error_class, error_value)
    267 @staticmethod
    268 def errorhandler_wrapper(
    269     connection: SnowflakeConnection | None,
   (...)
    272     error_value: dict[str, Any],
    273 ) -> None:
    274     """Error handler wrapper that calls the errorhandler method.
    275 
    276     Args:
   (...)
    287         exception to the first handler in that order.
    288     """
--> 290     handed_over = Error.hand_to_other_handler(
    291         connection,
    292         cursor,
    293         error_class,
    294         error_value,
    295     )
    296     if not handed_over:
    297         raise Error.errorhandler_make_exception(
    298             error_class,
    299             error_value,
    300         )

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\errors.py:348, in Error.hand_to_other_handler(connection, cursor, error_class, error_value)
    346     return True
    347 elif connection is not None:
--> 348     connection.errorhandler(connection, cursor, error_class, error_value)
    349     return True
    350 return False

File ~\AppData\Roaming\Python\Python39\site-packages\snowflake\connector\errors.py:221, in Error.default_errorhandler(connection, cursor, error_class, error_value)
    219 errno = error_value.get("errno")
    220 done_format_msg = error_value.get("done_format_msg")
--> 221 raise error_class(
    222     msg=error_value.get("msg"),
    223     errno=None if errno is None else int(errno),
    224     sqlstate=error_value.get("sqlstate"),
    225     sfqid=error_value.get("sfqid"),
    226     query=error_value.get("query"),
    227     done_format_msg=(
    228         None if done_format_msg is None else bool(done_format_msg)
    229     ),
    230     connection=connection,
    231     cursor=cursor,
    232 )

MethodNotAllowed: 000405: HTTP 405: Method not allowed

我尝试添加

C:\Users\{user}\AppData\Roaming\Python\Python39\site-packages\snowflake\connector
作为 PATH 环境变量。还尝试清除缓存认为这可以解决,但看不到任何其他原因这不起作用。我刚刚得到与上面相同的错误。

python-3.x error-handling snowflake-cloud-data-platform jupyter
1个回答
0
投票

我有相同的错误代码,问题是雪花帐户错误。但它不是通过 Jupyter。

© www.soinside.com 2019 - 2024. All rights reserved.