我目前在使用twisted python库访问通过https托管的内容时遇到一些问题。我是这个库的新手,我假设有一些我遗漏的概念导致了这个问题,但可能不是基于这个例子。在
以下是我收集示例的页面链接: https://twistedmatrix.com/documents/current/web/howto/client.html
在标题HTTP over SSL下
from twisted.python.log import err
from twisted.web.client import Agent
from twisted.internet import reactor
from twisted.internet.ssl import optionsForClientTLS
def display(response):
print("Received response")
print(response)
def main():
contextFactory = optionsForClientTLS(u"https://example.com/")
agent = Agent(reactor, contextFactory)
d = agent.request("GET", "https://example.com/")
d.addCallbacks(display, err)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()
if __name__ == "__main__":
main()
当运行这个代码时,它直接失败。我得到一个错误,如下所示:
这个错误使我相信传递到optionsForClientTLS的参数不正确。它需要一个主机名,而不是一个完整的url,因此我将参数缩短为example.com网站。一旦进行了更改,函数就成功完成了。在
但是不幸的是,在进行更改之后,脚本现在在调用代理请求。它提供的错误是:
Traceback (most recent call last):
File "https.py", line 19, in <module>
main()
File "https.py", line 13, in main
d = agent.request("GET", "https://example.com/")
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1596, in request
endpoint = self._getEndpoint(parsedURI)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1580, in _getEndpoint
return self._endpointFactory.endpointForURI(uri)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1456, in endpointForURI
uri.port)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 982, in creatorForNetloc
context = self._webContextFactory.getContext(hostname, port)
AttributeError: 'ClientTLSOptions' object has no attribute 'getContext'
这个错误使我相信optionsForClientTLS生成的对象不是预期在创建时传递给代理的对象类型。试图调用的函数不存在。说到这里,我有两个问题。在
是的,你绝对正确,文件上的例子是错误的。我注意到了错误while working w/ ^{} 。请尝试从v14开始跟踪this example。既然如此,您应该使用^{} ,而不是直接使用Twisted。大部分的重担都已为你处理好了。下面是一个简单的例子转换:
如您所见,
^{pr2}$treq
为您处理SSL内容。display()
回调函数可用于提取HTTP响应的各种组件,如标头、状态代码、正文等。如果只需要单个组件,例如响应正文,则可以进一步简化如下:相关问题 更多 >
编程相关推荐