Twisted HTTP Client访问对等IP(服务器)

时间:2017-02-03 10:03:22

标签: python twisted

如何在此Twisted HTTP Client示例中访问远程对等IP? (来自Twisted Docs)

使用此示例:

from sys import argv
from pprint import pformat

from twisted.internet.task import react
from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers


def cbRequest(response):
    #print 'Response version:', response.version
    #print 'Response code:', response.code
    #print 'Response phrase:', response.phrase
    #print 'Response headers:'
    #print pformat(list(response.headers.getAllRawHeaders()))
    poweredby = response.headers.getRawHeaders("X-Powered-By")
    server = response.headers.getRawHeaders("Server")


    print poweredby
    print server

    d = readBody(response)
    d.addCallback(cbBody)
    return d

def cbBody(body):
    print 'Response body:'
    #print body

def main(reactor, url=b"http://www.example.com/"):
    agent = Agent(reactor)
    d = agent.request(
        'GET', url,
        Headers({'User-Agent': ['Twisted Web Client Example']}),
        None)
    d.addCallback(cbRequest)



    return d

react(main, argv[1:])

在互联网上搜索SO后,我发现可以从以下网址阅读:

self.xmlstream.transport.getHandle().getpeername()

self.transport.getPeer()

但是,我不知道哪个班级"自我"是指和将它放在示例代码中的哪个位置?

有任何帮助吗?提示?想法?

谢谢,

1 个答案:

答案 0 :(得分:2)

可以获取地址,但你必须破解一些抽象层并触摸私有属性:

from __future__ import print_function
from twisted.web.client import Agent
from twisted.internet.task import react
from twisted.internet.protocol import Protocol
from twisted.internet.defer import Deferred

class ReadAddress(Protocol):
    def __init__(self):
        self.result = Deferred()

    def connectionMade(self):
        self.result.callback(self.transport._producer.getPeer())

def readAddress(response):
    p = ReadAddress()
    response.deliverBody(p)
    return p.result

@react
def main(reactor):
    a = Agent(reactor)
    d = a.request(b"GET", b"http://www.google.com/")
    d.addCallback(readAddress)
    d.addCallback(print)
    return d

理想情况下,会有一个更简单的(公共!)接口来检索这样的信息。如果您可以在Twisted跟踪器中提交功能请求,那就太棒了。