在Twisted客户端中生成标头

时间:2010-07-21 15:56:29

标签: python http client twisted

我正在使用Twisted web“HTTPClient”协议与http服务器对话(使用扭曲的应用程序作为客户端),问题是我的大多数请求都不接受我的标题。是否有某种方式(可能使用某些库)生成标题? 我会发布一些代码,以便你看看

class Local(HTTPClient):
def generateHeaders(self, type=None):
    self.sendHeader('User-Agent', 'Twisted Web Client')
    if type:
        self.sendHeader('Content-Type', 'x-www-form-urlencoded')
    self.sendHeader('Accept', '*/*')
    self.sendHeader('Host', 'localhost')
    self.endHeaders()

def connectionMade(self):
    ## GENERATE ID
    self.userid= self.generateID()
    self.sendCommand('POST', '/chat/action=join&user=pirosb3')
    self.generateHeaders(type=True)

def dataReceived(self, data):
    print data

正如你所看到的,我创建了一个为我生成标题的方法,但是我必须说,我总是得到错误响应。

任何人都知道解决方案吗?

由于

1 个答案:

答案 0 :(得分:3)

我肯定会建议您使用Twisted的Agent课程以及Header模块中的twisted.web.http_headers课程。

有一本很好的指南here

如果您需要Twisted HTTP客户端的实际示例,该客户端会向请求添加一些标头并且可以读取答案,这里是:

from pprint import pformat

from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

class BeginningPrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.remaining = 1024 * 10

    def dataReceived(self, bytes):
        if self.remaining:
            display = bytes[:self.remaining]
            print 'Some data received:'
            print display
            self.remaining -= len(display)

    def connectionLost(self, reason):
        print 'Finished receiving body:', reason.getErrorMessage()
        self.finished.callback(None)

agent = Agent(reactor)
d = agent.request(
    'GET',
    'http://example.com/',
    Headers({'User-Agent': ['Twisted Web Client Example']}),
    None)

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()))
    finished = Deferred()
    response.deliverBody(BeginningPrinter(finished))
    return finished
d.addCallback(cbRequest)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()