python 3.x urllib.request.HTTPSHandler 覆盖方法 GET POST

python 3.x urllib.request.HTTPSHandler override METHOD GET POST

context = ssl.create_default_context()
context.load_cert_chain(certificate, pkey)
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))
response = opener.open(url, data=None)
print(response.read())

使用 data=None 执行上述代码会自动将 METHOD 设置为 GET,而将 data 设置为任何其他内容会自动将 METHOD 设置为 POST.

有没有办法覆盖此行为?

根据文档,您可以使用 Request.method,但我不明白如何从 'opener' 中引用它。 https://docs.python.org/3/library/urllib.request.html

Request.method

The HTTP request method to use. By default its value is None, which means that get_method() will do its normal computation of the method to be used. Its value can be set (thus overriding the default computation in get_method()) either by providing a default value by setting it at the class level in a Request subclass, or by passing a value in to the Request constructor via the method argument.

New in version 3.3.

Changed in version 3.4: A default value can now be set in subclasses; >previously it could only be set via the constructor argument.

"method 应该是一个字符串,指示将使用的 HTTP 请求方法(例如 'HEAD')。如果提供,其值存储在方法属性中并由 get_method 使用()。如果数据为 None,则默认为 'GET',否则为 'POST'。Subclasses 可以通过在 [=31] 中设置 method 属性来指示不同的默认方法=] 本身。"

如果您使用 urllib.request.Request,您可以使用 method 参数来为这个请求设置您想要的特定 method

class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

但是 - 当您使用 opener 时,您无法提供 method:

OpenerDirector.open(url, data=None[, timeout])

open 方法没有 method 参数。


您可以做的是创建一个 Request 对象并使用 opener 发送该请求:

req = urllib.request.Request(url, method='POST')
res = opener.open(req)
print(res.read())