如何在使用M2Crypto SSL时禁用Python中的URL重定向?

0 投票
1 回答
585 浏览
提问于 2025-04-15 14:50

这是我的代码:

url_object = urlparse(url)
hostname = url_object.hostname
port = url_object.port
uri = url_object.path if url_object.path else '/'

ctx = SSL.Context()
if ctx.load_verify_locations(cafile='ca-bundle.crt') != 1: raise Exception("Could not load CA certificates.")
ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=5)
c = httpslib.HTTPSConnection(hostname, port, ssl_context=ctx)
c.request('GET', uri)
data = c.getresponse().read()
c.close()
return data

我该如何在这段代码中禁用网址重定向呢?我希望能在上面代码中的连接对象 'c' 上设置这个选项。

提前感谢你的帮助。

1 个回答

0

httpslib.HTTPSConnection 不会自动重定向。就像Lennart在评论中提到的,它是从 httplib.HTTPConnection 这个类派生出来的,而这个类也不会自动重定向。用 httplib 测试一下很简单:

import httplib

c = httplib.HTTPConnection('www.heikkitoivonen.net', 80)
c.request('GET', '/deadwinter/disclaimer.html')
data = c.getresponse().read()
c.close()
print data

这段代码会输出:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://www.heikkitoivonen.net/deadwinter/copyright.html">here</a>.</p>
</body></html>

你需要自己处理重定向的问题,使用 http(s)lib 时要注意,比如在我之前写的一个简单测试框架 silmut 中的 request 函数。

撰写回答