使用 Python urllib 获得安全连接的最佳方式
Best way to obtain a secure connection using Python urllib
希望有人能轻松回答这个问题。我正在 Python 中编写应用程序,部分应用程序使用 API 获取下载 link,然后使用 link 下载相应的服务器更新。目前,我正在使用 urllib.request.urlopen()
完成此操作,并且希望安全地进行此操作。因此,我想知道是否仅在 URL 中指定 https
就足够了,或者我是否必须另外使用上下文参数?
Python 文档在如何处理 HTTPS 请求方面有点含糊,但据我所知,现在在 URL 中指定 https
应该就足够了。
在 urllib.request.urlopen, there is a reference to the http.client.HTTPSConnection class in regards to the context parameter. In the documentation for the HTTPSConnection class, there is a link for security considerations 的文档中。在这里它指出:
For client use, if you don’t have any special requirements for your security policy, it is highly recommended that you use the create_default_context() function to create your SSL context. It will load the system’s trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings.
鉴于 urllib.request.urlopen()
上的文档显示上下文是一个可选参数,您可能不必使用它来建立安全的 https 连接,但考虑到安全注意事项部分所说的内容,我会使用
ssl.create_default_context()
作为良好实践生成上下文
urllib.request.urlopen("https://www.whosebug.com", context=ssl.create_default_context())
编辑
查看 urllib.request.urlopen
的源代码后,如果您未指定上下文但使用 https url,它似乎会为您提供默认上下文。如果您不为 urlopen()
提供上下文,它将调用 build_opener()
并在该函数的注释中声明
The opener will use several default handlers, including support
for HTTP, FTP and when applicable HTTPS.
所以最后的答案是你可以不提供任何上下文,它所需要的只是 url
希望有人能轻松回答这个问题。我正在 Python 中编写应用程序,部分应用程序使用 API 获取下载 link,然后使用 link 下载相应的服务器更新。目前,我正在使用 urllib.request.urlopen()
完成此操作,并且希望安全地进行此操作。因此,我想知道是否仅在 URL 中指定 https
就足够了,或者我是否必须另外使用上下文参数?
Python 文档在如何处理 HTTPS 请求方面有点含糊,但据我所知,现在在 URL 中指定 https
应该就足够了。
在 urllib.request.urlopen, there is a reference to the http.client.HTTPSConnection class in regards to the context parameter. In the documentation for the HTTPSConnection class, there is a link for security considerations 的文档中。在这里它指出:
For client use, if you don’t have any special requirements for your security policy, it is highly recommended that you use the create_default_context() function to create your SSL context. It will load the system’s trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings.
鉴于 urllib.request.urlopen()
上的文档显示上下文是一个可选参数,您可能不必使用它来建立安全的 https 连接,但考虑到安全注意事项部分所说的内容,我会使用
ssl.create_default_context()
作为良好实践生成上下文
urllib.request.urlopen("https://www.whosebug.com", context=ssl.create_default_context())
编辑
查看 urllib.request.urlopen
的源代码后,如果您未指定上下文但使用 https url,它似乎会为您提供默认上下文。如果您不为 urlopen()
提供上下文,它将调用 build_opener()
并在该函数的注释中声明
The opener will use several default handlers, including support for HTTP, FTP and when applicable HTTPS.
所以最后的答案是你可以不提供任何上下文,它所需要的只是 url