扭曲的HTTPS客户端

2024-09-20 00:09:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前在使用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生成的对象不是预期在创建时传递给代理的对象类型。试图调用的函数不存在。说到这里,我有两个问题。在

  1. 这个例子不推荐使用吗?前面的示例使http请求的工作都很有魅力。是我做错了什么,还是这个例子不再有效?在
  2. 我只想找一个简单的方法从服务器检索数据使用HTTPS。如果这样做不是解决方案,有人熟悉如何使用twisted发出HTTPS请求吗?在

Tags: infrompyhttpsimportcomclientweb
1条回答
网友
1楼 · 发布于 2024-09-20 00:09:05

是的,你绝对正确,文件上的例子是错误的。我注意到了错误while working w/ ^{}。请尝试从v14开始跟踪this example。既然如此,您应该使用^{},而不是直接使用Twisted。大部分的重担都已为你处理好了。下面是一个简单的例子转换:

from __future__ import print_function
import treq
from twisted.internet import defer, task
from twisted.python.log import err

@defer.inlineCallbacks
def display(response):
    content = yield treq.content(response)
    print('Content: {0}'.format(content))

def main(reactor):
    d = treq.get('https://twistedmatrix.com')
    d.addCallback(display)
    d.addErrback(err)
    return d

task.react(main)

如您所见,treq为您处理SSL内容。display()回调函数可用于提取HTTP响应的各种组件,如标头、状态代码、正文等。如果只需要单个组件,例如响应正文,则可以进一步简化如下:

^{pr2}$

相关问题 更多 >